How to Create a Class with Constructors and Destructors in C++?
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++
// C++ Program to illustrate how to Create a Class with // Constructors and Destructors #include <iostream> using namespace std; class GFG { public : // Default Constructor GFG() { cout << "Constructor called" << endl; } // Destructor ~GFG() { cout << "Destructor called" << endl; } }; int main() { // Creating an object of MyClass GFG obj; // Object goes out of scope // destructor is called return 0; } |
Output
Constructor called Destructor called
Contact Us