Site icon Learn C++

What Is The Typical Declaration Of A Destructor In A C++ App?

When you construct an object in your C++ app, sometimes you need operations to deconstruct. Destructors not only used in classes but also used with struct and union data types. Do you want to learn what is destructor or what kind of methods we have that we can declare and use destructors? In this post, we will try to explain how to use a Typical Destructor in Classes with given examples.

What is a constructor in C++?

The Constructor in C++ is a function, a method in the class, but it is a ‘special method’ that is automatically called when an object of a class is created. We don’t need to call this function. Whenever a new object of a class is created, the Constructor allows the class to initialize member variables or allocate storage. This is why the name Constructor is given to this special method. Here is a simple constructor class example below,

[crayon-6742ac588cd8c044982632/]

What is a destructor in C++?

The Destructor in classes (i.e class_name) is a special member function to delete objects, in other terms it is called when the lifetime of an object ends. The purpose of the destructor is to do operations when destruct the object. The object may have acquired or allocated data on memory on runtime, they need to be freed too when objects are being deleted, destructor is the function that frees the resources of the object. When we construct an object, sometimes we need operations to deconstruct. Destructors are not only used in classes but also used with struct and union data types.

[crayon-6742ac588cd96889907894/]

What is the typical declaration of a destructor in C++?

The Destructor in classes (i.e class_name) is a special member function to delete objects, in other terms it is called when the lifetime of an objects ends. The purpose of the destructor is to do operations when destruct the object. Object may have acquired or allocated data on memory on runtime, they need to be freed too when objects are being deleted, destructor is the function that free the resources of object.

To define a destructor in a class we use ‘~‘ symbol with the same class name and parenthesis as given below,

Syntax,

[crayon-6742ac588cd98354521305/]

Destructor declaration example in a class,

[crayon-6742ac588cd9a535167772/]

An example to destructor method in C++,

[crayon-6742ac588cd9b279480153/]

You can try this example for yourself today – download a free trial of C++ Builder.

Exit mobile version