Using initialization lists with inherited variables

I worked on the program for about 20 minutes, and I found that for some reason it would not allow me to use inherited variables in initialization lists. This program, for example:

class A { protected: int i; }; class B : public A { public: B() : i(45) { } }; int main() { B b; } 

Gives an error

error: class 'B has no field named' i

However, if you change the constructor to this:

 B() { i = 45; } 

It compiles.

I never knew that you cannot initialize inherited variables. My question is why?

+4
source share
3 answers

An object can only be initialized once: when it first appears.

A initializes all its member variables in its constructor (before its constructor is executed). Thus, B cannot initialize the member variable from A , since the member variable has already been initialized by constructor A

(In this particular case, technically, i remains uninitialized because A did not initialize it, however, it is still A responsible for initializing its member variables.)

+10
source

You cannot do this in C ++. The usual way is to have a constructor ( protected ) in the parent class that accepts the parameter used to set the variable.

The use of protected attributes like this is almost never suggested, since it allows child classes to violate the invariants of the parent class, which in the future will cause severe debugging headaches.

+4
source

You must define an open constructor with a parameter in class A. Then in class B use the constructor from the base class. Example:

 #include <iostream> using namespace std; class A { protected: int i; public: A(int number) : i(number) {} }; class B : public A { public: B() : A(45) { } }; int main() { B b; } 
+2
source

All Articles