Welcome to the fascinating world of C++! Today, we're diving deep into a crucial aspect of object-oriented programming: Destructors in Inheritance. š
A destructor is a special function in C++ that is automatically called when an object goes out of scope or is deleted. Its purpose is to clean up any resources (like memory) allocated by the object during its lifetime.
Let's first understand destructors in simple classes before moving to inheritance.
#include <iostream>
class SimpleClass {
public:
// Constructor
SimpleClass() {
std::cout << "Constructing SimpleClass\n";
// Resource allocation
data = new int;
}
// Destructor
~SimpleClass() {
std::cout << "Destroying SimpleClass\n";
// Resource deallocation
delete data;
}
private:
int *data;
};In the above example, we have a simple class SimpleClass with a constructor and a destructor. The constructor allocates memory for an integer, and the destructor deallocates it.
Now, let's see how destructors work in inheritance.
#include <iostream>
class Base {
public:
Base() {
std::cout << "Constructing Base\n";
data = new int;
}
~Base() {
std::cout << "Destroying Base\n";
delete data;
}
private:
int *data;
};
class Derived : public Base {
public:
Derived() {
std::cout << "Constructing Derived\n";
}
~Derived() {
std::cout << "Destroying Derived\n";
}
};In the above example, we have a base class Base and a derived class Derived. The derived class inherits the constructor and destructor from the base class. When we create an object of the derived class, the constructor of the derived class is called first, followed by the constructor of the base class. Similarly, when the object goes out of scope, the destructor of the base class is called first, followed by the destructor of the derived class.
When dealing with polymorphism, it's important to ensure that the correct destructor is called for each object, regardless of the type of the pointer or reference pointing to it. This is achieved by making the destructor virtual.
#include <iostream>
class Base {
public:
virtual ~Base() {
std::cout << "Destroying Base\n";
}
};
class Derived : public Base {
public:
~Derived() {
std::cout << "Destroying Derived\n";
}
};
int main() {
Base *base = new Derived(); // Upcasting
delete base; // The virtual destructor ensures that Derived's destructor is called
return 0;
}In the above example, we have a Base class with a virtual destructor and a Derived class that inherits from Base. In the main function, we create a Derived object and upcast it to a Base pointer. When we delete the Base pointer, the virtual destructor ensures that the correct destructor is called for the Derived object.
What is the purpose of a destructor in C++?
In C++, when is the destructor called for a derived class in an inheritance hierarchy?