Table of Contents
In this article, you’ll learn about how to make C++ program to add constructor and destructor for initializing and destroying objects with explanation.
What Does Constructor Mean?
A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.
What Does Destructor Mean?
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ).
C++ program to add constructor and destructor for initializing & destroying objects
#include <iostream>
class Example {
public:
// Constructor
Example() {
std::cout << "Constructor called." << std::endl;
}
// Destructor
~Example() {
std::cout << "Destructor called." << std::endl;
}
};
int main() {
Example ex; // Create an object of class Example
return 0;
}
In this program, we define a class called “Example” that has a constructor and destructor. The constructor is defined with the syntax Example()
, which indicates that it takes no arguments. In the body of the constructor, we print out a message to indicate that the constructor has been called.
The destructor is defined with the syntax ~Example()
, which indicates that it has the same name as the class but with a tilde (~
) in front of it. Like the constructor, it takes no arguments. In the body of the destructor, we print out a message to indicate that the destructor has been called.
In the main
function, we create an object of the Example
class by simply declaring a variable of type Example
. When the main
function finishes executing and the ex
object goes out of scope, the destructor is automatically called to clean up any resources that the object was using.
That’s a simple example of how to add a constructor and destructor to a class in C++. The constructor is called when an object of the class is created, and the destructor is called when the object is destroyed. This can be useful for initializing and cleaning up resources that the object uses.