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?
Use super(). __init()__ to call the immediate parent class constructor in Python. Calling a parent constructor within a child class executes the operations of the parent class constructor in the child class.
base (C# Reference)The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.
Example of Base Class Constructor Calling When we create the object of Pqr class then first it will call Pqr class constructor but Pqr class constructor first initialize the base class constructor then Pqr constructor will be initialized.
Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With