Question

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?

Was it helpful?

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

OTHER TIPS

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.

You must define public constructor with parameter in class A. Then in class B use to constructor from 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top