Conteúdo do Curso
C++ OOP
C++ OOP
Constructor 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.
main
#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.
main
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.
main
#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.
Obrigado pelo seu feedback!