Data Member Initialization Question const

Asked

Viewed 73 times

2

"The 'constancy' of a const object is imposed from the moment the constructor completes the initialization of the object until the destructor of that object is called" - Deitel,++

If the compiler "considers" a member to be present after the initialization of the object by the constructor, why does an attribution initialization generate errors ? Why only one boot per member initializer is accepted ?

Examples:

class Example
{ 
   public:
    const int num1;
    int num2;   

   Example(int a, int b)  
   {
      num1 = a; // Gera um erro
      num2 = b;
   }    
}

class Example
{ 
   public:
    const int num1;
    int num2;   

   Example(int a, int b)
    : num1(a) // Funciona normalmente
   {
      num2 = b; 
   }    
}

1 answer

2


Why only one boot per member initializer is accepted ?

Simple. Initialization of the members is complete before the constructor body starts executing.

This from here:

num1 = a;

It is assignment, not initialization. Assignment in constant variables is forbidden in the language. Now, this from here:

Example(int a, int b) : num1(a) { ...

It is initialization. It would be the same as doing:

const int num1(42);

Or:

const int num1 = 42;

'Cause when you use the = in the variable declaration, it is considered as initialization, and not assignment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.