Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer List for Derived Class

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’

like image 534
Willy Goat Avatar asked Jan 07 '23 09:01

Willy Goat


2 Answers

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
}
like image 128
Brian Bi Avatar answered Jan 19 '23 21:01

Brian Bi


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

like image 27
Samboy786 Avatar answered Jan 19 '23 21:01

Samboy786