Welcome to our comprehensive guide on C++ Constructor in Inheritance! This lesson is designed to help both beginners and intermediates understand the intricacies of constructors in the context of inheritance. Let's dive in!
A constructor in C++ is a special function that is used to initialize objects. Contrary to other functions, constructors don't have a return type, not even void.
class MyClass {
public:
MyClass() { // constructor body } // default constructor
};Every time you create an object of MyClass, the constructor gets called automatically.
When a child class inherits from a parent class, it inherits the parent's data members and member functions. However, constructors are not inherited. Instead, there are specific rules for constructing objects of derived classes.
To call a base class constructor in the derived class constructor, we use a constructor initialization list. The constructor initialization list is a comma-separated list of base class constructors that are called before the body of the constructor is executed.
class Parent {
public:
Parent(int x) { cout << "Parent constructor called with " << x << endl; }
};
class Child : public Parent {
int childData;
public:
Child(int x, int y) : Parent(x) { childData = y; cout << "Child constructor called with " << y << endl; }
};In the above example, when we create a Child object, first the Parent constructor is called with the argument x, and then the body of the Child constructor is executed.
Which function is not inherited in C++ when a child class inherits from a parent class?
When a derived class inherits from a base class and does not provide its own constructor, a default constructor for the derived class will not be generated if the base class does not have a default constructor. In such a case, a compile-time error will occur. To avoid this, you can either provide a default constructor in the base class or make the base class constructor protected or private and provide a default constructor in the derived class that initializes the base class using the constructor initialization list.
That's all for this lesson! Stay tuned for more on C++ programming at CodeYourCraft. Happy coding! ā