Calling the base class constructor from the derived class constructor
First off, a PetStore
is not a farm.
Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:
Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);
These are the methods you're given access to and these are the ones you should use.
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 ??
Simple, you call addAnimal
. It's public
and it also increments sizeF
.
Also, note that
PetStore()
{
idF=0;
};
is equivalent to
PetStore() : Farm()
{
idF=0;
};
i.e. the base constructor is called, base members are initialized.
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 initialize
sizeF
, by calling the constructor of Farm
. The constructor of a class always calls the constructors of
all of its base classes and all of its members.)
The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:
class PetStore: public Farm
{
public :
PetStore()
: Farm() // <---- Call base-class constructor in initialision list
{
idF=0;
};
private:
int idF;
string nameF;
}