Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
Seth Carnegie Avatar asked Dec 04 '22 21:12

Seth Carnegie


2 Answers

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.)

like image 197
James McNellis Avatar answered Jan 02 '23 04:01

James McNellis


You can't do this in C++. The normal way is to have a (protected) constructor in the parent class that takes a parameter used to set the variable.

Using protected attributes like this is almost never suggested because it lets child classes violate parent class invariants which is only going to caused severe debugging headaches later on.

like image 32
Mark B Avatar answered Jan 02 '23 06:01

Mark B