Abhishek Ghadge
Abhishek Ghadge

Reputation: 435

Relation between base class constructor arguements with derived class constructor

I cannot understand this statement:"If the base class has constructor with arguments,then it is mandatory for derived class to have constructor and pass arguments to base class constructor." Please use some program if you can.

Upvotes: 1

Views: 191

Answers (1)

bhristov
bhristov

Reputation: 3187

If you have a base class called Animal and a derived class named Dog. You will want to call Animal's constructor inside of Dog's constructor to initialize the inherited member variables. A very basic example looks like this:

class Animal
{
int num_legs;
public:
Animal(int legs): num_legs(legs){}
};

class Dog: public Animal
{
public:
// now we send the number of legs to the Base class
Dog(int legs): Animal(legs) {}
};

If you rely on the default constructor of Dog, you will end up with an uninitialized variable for legs in this case.

Upvotes: 1

Related Questions