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?
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With