Calling the base class constructor from the derived class constructor

Joy picture Joy · Apr 23, 2012 · Viewed 153.4k times · Source

I have a question:

Say I have originally these classes which I can't change (let's say because they're taken from a library which I'm using):

class Animal_
{
public:
    Animal_();
    int getIdA()
    {
        return idA;
    };
    string getNameA()
    {
        return nameA;
    }
private:
    string nameA;
    int idA;
}

class Farm
{
public :
    Farm()
    {
        sizeF=0;
    }
    Animal_* getAnimal_(int i)
    {
        return animals_[i];
    }
    void addAnimal_(Animal_* newAnimal)
    {
        animals_[sizeF]=newAnimal;
        sizeF++;
    }
    
private:
    int sizeF;
    Animal_* animals_[max];
}

But then I needed a class where I just add couple of fields so I did this:

class PetStore : public Farm
{
public :
    PetStore()
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

However, I can't initialize my derived class. I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that? I'm thinking maybe in the PetStore default constructor I can call Farm()... so any idea?

Answer

James Kanze picture James Kanze · Apr 23, 2012

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)