VOOZH about

URL: https://www.geeksforgeeks.org/cpp/create-class-with-constructors-and-destructors-in-cpp/

⇱ How to Create a Class with Constructors and Destructors in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a Class with Constructors and Destructors in C++?

Last Updated : 23 Jul, 2025

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


Output
Constructor called
Destructor called
Comment
Article Tags: