New course! Every coder should learn Generative AI!
Try a free lesson0
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
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.
+ 1
such feature is scheduled for C++20.
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`
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.
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.