Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is modify const in constructor C++ standard?

Is modify const in constructor C++ standard? I was modifying my struct removing fixed-values(default member initializer) to set it later, at constructor-time but I forget to remove const keyword and noticied it later. To my surprise I didn't get a compile-error, it just worked fine but for test case 2 it give a compiler. How are they different?

test case 1:

struct A
{
    const int x = 2;

    A()
        : x(3)
    {
    }
};

test case 2:

struct A
{
    const int x = 2;

    A()
    {
           x = 3; // compile error!  error: read-only variable is not assignable
    }
};
like image 434
The Mask Avatar asked Mar 27 '14 21:03

The Mask


3 Answers

In the first example you are initializing the constant variable, in the second you are assigning a value to it, after the variable is default constructed. These are different operations and assignment is not possible for constants after their initialization.

like image 58
Marius Bancila Avatar answered Nov 10 '22 14:11

Marius Bancila


This syntax was added in C++11:

struct A
{
    const int x = 2;

In this case the 2 is like a "default" value to be used for initialization of x. If you initialize x in your constructor's initialization list, then that is the value used. However if you did not do so, then 2 is used.

This was added to C++11 to avoid the tedium of having to repeat things in the initialization lists if you had multiple constructors.

like image 3
M.M Avatar answered Nov 10 '22 14:11

M.M


  1. The thing is that the object must be fully initialized before the body of your constructor can proceed to start playing with it. This means that there must be reserved enough space in memory to which the instance of new object will be placed.

  2. If you declare data member (int x) to be const, you prohibit yourself from ever changing it's value, once it is created, this means that the value must be set during it's creation.

In example 1 you first create the int x and set it to value 3 (which will reside in memory reserved for your object) and only after that the body of your constructor executes.

In example 2 you create new object (with some value for your int x) and than you try to modify it in your constructor, which is prohibited by the const keyword.

like image 1
Kupto Avatar answered Nov 10 '22 15:11

Kupto