Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived Class Constructor Calls

If I have a base class:

class Base{
  ...
};

and a derived class

class Derived : public Base{
  ...
}

does this derived class always call the default constructor of the base class? i.e. the constructor that takes no parameters? For example If I define a constructor for the base class:

Base(int newValue);

but I do not define the default constructor(the parameterless constructor):

Base();

(I recognize this is only a declaration and not a definition) I get an error, until I define the default constructor that takes no parameters. Is this because the default constructor of a base class is the one that gets called by a derived class?

like image 905
kjh Avatar asked Nov 19 '12 00:11

kjh


2 Answers

Yes, by default, the default constructor is called. You can go around this by explicitly calling a non-default constructor:

class Derived : public Base{
    Derived() : Base(5) {}
};

This will call the base constructor that takes a parameter and you no longer have to declare the default constructor in the base class.

like image 55
Luchian Grigore Avatar answered Sep 23 '22 23:09

Luchian Grigore


The reason why default constructor is called is that in case if you have created any object and at that instance you have not passed arguments (you may want to initialize them later in the program). This is the most general case, that's why calling default constructor is necessary.

like image 33
nikhil Avatar answered Sep 23 '22 23:09

nikhil