cellh
cellh

Reputation: 11

Question about protected members in inheritance

I am lead to believe that protected members are accessible by inheriting classes. So, what is my error in thought process in believing this is ok?

I have some class, Food and Veg, where Veg inherits from Food. Food has a protected member int age; In the constructor of Veg, I try to initialize age to 0. Why is this not valid?

Some code...

Veg::Veg():age(0)
{
    cout << "Veg constructor." << endl;
}

class Veg : public Food
{
//snip
};

class Food
{
//snip
protected:
    int age;
};

Upvotes: 1

Views: 182

Answers (2)

justin
justin

Reputation: 104708

that's how initialization lists have been designed; the class which declares the member is responsible for initialization in this case.

typically, this is overcome by Food exposing age as an argument in the constructor:

Food::Food(const int& inAge) : age(inAge) {}
Veg::Veg() : Food(-1) {}

although, you can still access age in the ctor's body, if protected:

Veg::Veg() : Food() {this->age = -1;}

if it weren't this way, then you'd construct age twice, which often matters when the typeof age is something more complex than an int.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355237

In an initialization list for a constructor for a class C, you can only initialize

  1. direct base classes of class C,
  2. virtual base classes of class C, and
  3. nonstatic data members of class C.

If you want to initialize a data member of a base class, you need to do so either in the initialization list of the base class's constructor or in the body of the derived class's constructor. You can't do it in the initialization list of the derived class's constructor.

Upvotes: 7

Related Questions