Why should const elements be initialized in the constructor initializer, and not in its body?

Why are classes declared as const initialized in the list of constructor initializers and not in the constructor body?

What is the difference between the two?

+55
c ++ constructor initialization const
Dec 10 '08 at 6:35
source share
3 answers

In C ++, an object is considered fully initialized when execution enters the body of the constructor.

You said:

"I wanted to know why const should be intialized in the constructor initializer and not in the body?"

What you are missing is that the initialization takes place in the initialization list, and the assignment takes place in the constructor body. Stages of logic:

1) The const object can only be initialized.

2) An object has all its elements initialized in the initialization list. Even if you do not explicitly initialize them there, the compiler will gladly do it for you :-)

3) Therefore, putting 1) and 2) together, a member that is constant can ever have the value assigned to it during initialization, which occurs during the initialization list.

+90
Dec 10 '08 at 7:01
source share

const , and reference variables must be initialized in the declared string.

  class Something { private: const int m_nValue; public: Something() { m_nValue = 5; } }; 

will generate code equivalent to:

 const int nValue; // error, const vars must be assigned values immediately nValue = 5; 

Assigning values ​​to const variables or reference elements in the constructor body is not enough.

C ++ provides another way to initialize member variables, which allows you to initialize member variables when they are created, not later. This is done using an initialization list.

You can assign values ​​to variables in two ways: explicitly and implicitly: view a plain copy in clipboardprint?

 int nValue = 5; // explicit assignment double dValue(4.7); // implicit assignment 

Using an initialization list is very similar to doing implicit assignments.

Remember that the member initialization list used to initialize the underlying and data object objects is in the definition, not the constructor declaration.

Learn more about cpp-tutorial and Code Wrangler .

+9
Dec 10 '08 at 6:57
source share

Because persistent variables and references must be initialized during ie declaration before use. But constructors assign a value to a variable that does not initialize the variable, so you should use the initialization list for constant and reference

-2
Aug 12 '16 at 9:05
source share



All Articles