Is constructor allowed to be constexpr | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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
5 Answers
+ 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
+ 1
such feature is scheduled for C++20.
23rd Sep 2023, 9:02 AM
MO ELomari
0
1. In this code, we define a class called `test`. 2. Inside the class, there are three private member variables: `a`, `b`, and `c`. `a` and `b` are declared as `const` and `c` is an `int`. 3. The class `test` has a constructor that takes two integer parameters `a_val` and `b_val`. It initializes `a` and `b` with the provided values and sets `c` to 0. 4. The class also contains two `constexpr` member functions: `add` and `getC`. - `add` returns the sum of `a` and `b`
21st Sep 2023, 7:25 PM
Knight
Knight - 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