Explain constructors in derived class?

All QuestionsCategory: Cpp LanguageExplain constructors in derived class?
Chetan Shidling Staff asked 5 years ago

I need short information.

1 Answers
Best Answer
Chetan Shidling Staff answered 5 years ago
  1. Constructors play an important role in initializing objects.
  2. If the default constructor without argument is declared in the base class then the derived class need not have a constructor function.
  3. The compiler by default calls the base class constructor.

Example:

#include <iostream>
using namespace std;
class base
{
public:
base()
{
cout<<“base class constructor\n”; //default constructor
}
};
class derived : public base
{
public:
derived() //derived class constructor
{
//base :: base(); by default complier will call the base class constructor
cout<<“Derived class constructors\n”;
}
};
int main()
{
derived d;
return 0;
}

Output:

base class constructor
Derived class constructors