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-663490dfca186262678748/]

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-663490dfca18e066012508/]

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-663490dfca191785400906/]

Destructor declaration example in a class,

[crayon-663490dfca193749057145/]

An example to destructor method in C++,

[crayon-663490dfca195118112383/]

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

Exit mobile version