How to Create a Class with Constructors and Destructors in C++?
Last Updated :
27 Feb, 2024
In C++, a class is a user-defined data type encapsulating data members and member functions. The constructors and destructors are special member functions of a class used for initializing objects and cleaning up resources respectively. In this article, we will discuss how to create a class with constructors and destructors in C++.
Create a Class with Constructors and Destructors in C++
In C++, the compiler automatically creates a default constructor and a destructor for a class. But we can also define our own constructor and destructor to customize the behavior of our class.
Approach
- Define Constructor: Declare the constructor with the same name as the class without any return type. Add the parameters if required. Define this constructor inside its body.
- Define Destructor: Declare the destructor with a class name preceded by a tilde (~). The Destructors do not accept parameters and have no return type. But can still define it inside its body.
Syntax to Create Constructors and Destructors
// Constructor
ClassName() {
// Constructor logic
}
// Destructor implementation
~ClassName() {
// Destructor logic
}
C++ Program to Create a Class with Constructors and Destructors
C++
#include <iostream>
using namespace std;
class GFG {
public :
GFG() { cout << "Constructor called" << endl; }
~GFG() { cout << "Destructor called" << endl; }
};
int main()
{
GFG obj;
return 0;
}
|
Output
Constructor called
Destructor called
Share your thoughts in the comments
Please Login to comment...