Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Constructor and Destructor in Inheritance | Inheritance Overview
C++ OOP
course content

Зміст курсу

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

bookConstructor and Destructor in Inheritance

Base Class Constructor First

In the context of inheritance, constructors play a vital role in initializing derived classes correctly. Understanding the sequence in which constructors are invoked is key to grasping inheritance dynamics. Look at the output of the code snippet below to see the order of constructors calls.

cpp

main

copy
12345678910111213141516
#include <iostream> class Base { public: Base() { std::cout << "Base constructor called" << std::endl; } }; class Derived : public Base { public: Derived() { std::cout << "Derived constructor called" << std::endl; } }; int main() { Derived derivedObj; }

Remember

Once the Base Class constructor has completed its initialization, the Derived Class constructor is executed.

The superclass is called first because it has to initialize the inherited members of the subclass. This ensures that the subclass starts with a valid state and can rely on the initialized state of its base class.

cpp

main

copy
123456789101112131415161718
class Base { public: Base(int value) : data(value) {} private: int data; }; class Derived : public Base { public: Derived(int value) : Base(value) {} }; int main() { }

In the example we call constructor with parameters in initializer list. You have to explicitly call the superclass constructor within the initializer list of the subclass constructor. If you don't specify a base class constructor in the initializer list, the default constructor of the superclass is called automatically.

Derived Class Destructor First

When an object is destroyed, destructors are invoked in the reverse order of their constructors. This means that destructors are called for the most derived class first and then for each base class in the reverse order of their declaration.

cpp

main

copy
12345678910111213141516
#include <iostream> class Base { public: ~Base() { std::cout << "Base destructor called" << std::endl; } }; class Derived : public Base { public: ~Derived() { std::cout << "Derived destructor called" << std::endl; } }; int main() { Derived derivedObj; }

Remember

Only after the Base Class destructor has finished its cleanup, the Derived Class destructor is invoked.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 4
some-alt