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?
This question is related to
c++
inheritance
constructor
visibility
derived-class
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.
but 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 ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
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;
}
Source: Stackoverflow.com