Constructor and Destructor Behavior in Inheritance
- Constructor Execution: When an object of the derived class is created, the constructor of the base class executes first, followed by the constructor of the derived class.
- Destructor Execution: The destructor of the derived class is executed first, followed by the base class destructor, in reverse order of construction.
- Chaining Constructors: Constructors can be passed values to the base class using initializer lists.
Example:
class Base {
public:
Base() { cout << “Base Constructor”; }
~Base() { cout << “Base Destructor”; }
};
class Derived : public Base {
public:
Derived() { cout << “Derived Constructor”; }
~Derived() { cout << “Derived Destructor”; }
};
12.5 Function Overriding and Virtual Functions
- Function Overriding allows a derived class to provide a specific implementation of a function that is already defined in its base class.
- To ensure correct runtime behavior, use virtual functions. This supports runtime polymorphism.
Example:
class Base {
public:
virtual void show() { cout << “Base show”; }
};
class Derived : public Base {
public:
void show() override { cout << “Derived show”; }
};