Search code examples
c++inheritanceinitializer-list

Using initializer lists with inherited variables


I've been fiddling with a program for about 20 minutes and I found that for some reason it won't let me 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;
}

Will give the error

error: class ‘B’ does not have any field named ‘i’

However, if you change the constructor to this:

B() { i = 45; }

It compiles.

I never knew you can't initialize inherited variables. My question is, why?


Solution

  • An object can only be initialized once: when it first comes into existence.

    A initializes all of its member variables in its constructor (before the body of its constructor is executed). Thus, B cannot initialize a member variable of A because the member variable was already initialized by the constructor of A.

    (In this specific case, technically i is left uninitialized because A did not initialize it; that said, it is still A's responsibility to initialize its member variables.)