Home > Article > Backend Development > What role does destructor play in polymorphism in C++?
Destructors are crucial in C++ polymorphism, ensuring that derived class objects properly clean up memory when they are destroyed. Polymorphism allows objects of different types to respond to the same method call. The destructor is automatically called when an object is destroyed to release its memory. The derived class destructor calls the base class destructor to ensure that the base class memory is released.
The role of destructor in polymorphism in C++
The role of destructor in polymorphism in C++ It plays a vital role in ensuring that the memory of derived class objects is cleaned up in an appropriate manner when they are destroyed.
Introduction to Polymorphism
Polymorphism refers to the ability to allow objects of different types to respond to the same method call. In C++, this is accomplished through inheritance and virtual functions.
Destructor
The destructor is a special member function associated with a class that is automatically called when an object of that class is destroyed. It is responsible for freeing any memory or resources allocated by the object.
The role of destructor in polymorphism
When a derived class object is created, memory will be allocated to store data members unique to the derived class. However, when the derived class object is destroyed, the memory of the base class also needs to be released. The destructor ensures this by calling the base class destructor.
Practical case
Consider the following code:
class Base { public: Base() { std::cout << "Base constructed" << std::endl; } virtual ~Base() { std::cout << "Base destructed" << std::endl; } }; class Derived : public Base { public: Derived() { std::cout << "Derived constructed" << std::endl; } ~Derived() { std::cout << "Derived destructed" << std::endl; } }; int main() { Base* base = new Derived(); delete base; return 0; }
Output:
Base constructed Derived constructed Derived destructed Base destructed
In this example , the Derived
class is derived from the Base
class. When a Derived
object is created via the new
operator, both the Derived
and Base
constructors are called. When the object is destroyed through the delete
operator, the Derived
destructor will be called first to release the memory of the Derived
class. Then, the Base
destructor will be called to release the memory of the Base
class.
The above is the detailed content of What role does destructor play in polymorphism in C++?. For more information, please follow other related articles on the PHP Chinese website!