Open In App

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

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++ 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
Article Tags :