5

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’

Willy Goat
  • 1,175
  • 2
  • 9
  • 24

2 Answers2

8

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
}
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • I would hasten to clarify for readers who are new(er) to OOP - an object is (roughly) an instance of a class, so while you can have multiple objects of the same class, each of those objects can only be initialized once. – CodeMouse92 Oct 13 '15 at 00:22
  • 1
    @JasonMc92 An `int` is also an object in C++. An object is a region of storage. – Brian Bi Oct 13 '15 at 00:23
  • Yes, I know. I'm just putting that note of clarification. Way back when I learned OOP, I used to get confused between "class" and "object", so I'm just lending a little extra clarity for those groups. :D – CodeMouse92 Oct 13 '15 at 00:26
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++)

Community
  • 1
  • 1
Samboy786
  • 101
  • 1
  • 8