Is constructor allowed to be constexpr | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Is constructor allowed to be constexpr

Hi Refer code below: I have query related to constructor marked as constexpr. If I am not wrong, member function which csn be marked as const are the one which are eligible for constexpr. Constructor always modify member variables. But in this code, it initializes values from member initializer list. So far so good. Then i intentionally incremented c value from constructor body using ++c Still constexpr constructor is not throwing any error. Is this expected or I am missing something ? https://code.sololearn.com/cF95Bt1XwU1F/?ref=app

21st Sep 2023, 6:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 ответов
+ 1
since C++14 a constexpr member function or constexpr constructor can modify members of a class type as long as the lifetime of the object is contained within the evaluation of the constant expression.
22nd Sep 2023, 8:27 PM
MO ELomari
MO ELomari - avatar
+ 1
such feature is scheduled for C++20.
23rd Sep 2023, 9:02 AM
MO ELomari
MO ELomari - avatar
0
I got your point KnightBits but from third point, you missed a statement in body indicating ++c. and that is not const operaton. i am still confused why constexpr constructor does not error out as c is modified in constructor body.
22nd Sep 2023, 3:59 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thanks MO ELomari Does this mean only stack allocated members are allowed to be modified inside const constructor ? Heap allocated are also controlled by object itself though.
23rd Sep 2023, 3:27 AM
Ketan Lalcheta
Ketan Lalcheta - avatar