C++ Inheritance Mechanisms and Constructor Behavior
C++ supports both single inheritance and multiple inheritance. Single inheritance involves deriving from one base class, whereas multiple inheritance allows derivation from several base classes.
In Java, class inheritanec is limited to a single parent using the extends keyword, while implementing multiple interfaces is permitted through the implements keyword.
A derived class in C++ corresponds to what is known as a subclass in Java.
To declare a derived class in C++, place a colon (:) after the class name followed by the access specifier and base class name:
class Derived : public Base {
// class body
};
The access specifier can be public, private, or protected. For example:
class Derived : private Base {
// class body
};
Multiple inheritance allows specifying different access levels for each base class:
class Derived : public Base1, private Base2 {
// class body
};
In this case, members inherited from Base1 maintain their orgiinal access level, while those from Base2 become private within the derived class. Specifically, public and protected members of Base2 are treated as private in Derived, and private members of Base2 remain inaccessible.
Constructor and destructor execution order follows a specific pattern:
#include <iostream>
using namespace std;
class Parent {
public:
Parent() { cout << "Constructing parent\n"; }
~Parent() { cout << "Destroying parent\n"; }
};
class Child : public Parent {
public:
Child() { cout << "Constructing child\n"; }
~Child() { cout << "Destroying child\n"; }
};
int main() {
Child jack;
return 0;
}
Output demonstrates that the parent constructor runs before the child constructor, and during destruction, the child destructor executes before the parent destructor.