问题
I want to have a derived class which has a default constructor that initializes the inheirited members.
Why can I do this
class base{
protected:
int data;
};
class derived: public base{
public:
derived(){ //note
data = 42;
}
};
int main(){
derived d();
}
But not this
class base{
protected:
int data;
};
class derived: public base{
public:
derived(): //note
data(42){}
};
int main(){
derived d();
}
error: class ‘derived’ does not have any field named ‘data’
回答1:
An object can only be initialized once. (The exception is if you initialize it and then destroy it; then you can initialize it again later.)
If you could do what you're trying to do, then base::data
could potentially be initialized twice. Some constructor of base
might initialize it (although in your particular case it doesn't) and then the derived
constructor would be initializing it, potentially for a second time. To prevent this, the language only allows a constructor to initialize its own class's members.
Initialization is distinct from assignment. Assigning to data
is no problem: you can only initialize data
once but you can assign to it as many times as you want.
You might want to write a constructor for base
that takes a value for data
.
class base{
protected:
int data;
base(int data): data(data) {}
};
class derived: public base{
public:
derived(): base(42) {}
};
int main(){
derived d{}; // note: use curly braces to avoid declaring a function
}
回答2:
You need a base class constructor for this job. You can look for more explanation here -
Initialize parent's protected members with initialization list (C++)
来源:https://stackoverflow.com/questions/33092076/initializer-list-for-derived-class