C++ Programming

C++ Destructor And Difference Between Constructor And Destructor

Destructors:

C++ Destructor: When an object is destroyed, a special member function of that class is executed automatically. This member function is called the destructor function or destructor. The C++ destructor function has the same name as the name of a class but a tilde sign (~) is written before its name. It is executed automatically when an object comes to the end of its life.

Like constructors, C++ destructors do not return any value. They also do not take any arguments.

For example, a local object is destroyed when all the statements of the function in which it is declared are executed. So at the end of the function, the C++ destructor function is executed.

Similarly, global object (objects that are declared before the main function) or static object is destroyed at the end of the main function. The lifetime of these objects ends when the program execution ends. So at the end of the program, the destructor function is executed. The C++ destructor functions are commonly used to free the memory that was allocated for objects.

The following example explains the concept of constructors and destructors.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Example: how to use C++ constructor and C++ destructor:

#include <iostream>

using namespace std;
class data
{
    public:
    data()
    {
        cout<<"This is constructor function"<<endl;
    }
    ~data()
    {
        cout<<"this is destructor function"<<endl;
    }
};
int main()
{
    data x;
    int a,b;
    a=20;
    b=40;
    cout<<"Sum of two number is = "<<(a+b)<<endl;

    return 0;
}
Output:
This is constructor function
Sum of two number is = 60
this is destructor function

Passing objects as Arguments:

Objects can also be passed as an argument to the member function. When an object is passed as an argument to a member function:

  • Only the name of the object is written in the argument.
  • The number of parameters and their types must be defined in the member function to which the object is to be passed. The object that is passed is treated locally for the member function and are destroyed when the control returns to the calling function.



Example: how to use passing objects as arguments in c++ destructor:

#include <iostream>

using namespace std;
class data
{
    private:
    char name[15];
    public:
    void get_data(void)
    {
        cout<<"Enter your name: ";
        cin>>name;
    }
    void show_data(data s)
    {
        cout<<"Name is: "<<s.name<<endl;
    }
};
int main()
{
    data temp, abc;
    temp.get_data();
    abc.show_data(temp);

    return 0;
}
Output:
Enter your name: Electronic clinic
Name is: Electronic

In the above program, the class “data” has one data member “name” of string type and two member function “get_data” and “show_data”. The  “show_data” function has an argument of class “data” type.

The object “temp” and “abc” are declared of class “data”. The member function gets the name in object “temp” and store it into the data member “name”.  the member function “show_data” for object “abc” is called by passing argument of object “temp” when the control shifts to the member function “show_data” a copy of “temp” is created as a local object in the show_data function with name “s”

Another Example:

For example, a class called data will have the destructor ~data(). Additionally, C++ destructors have neither parameters nor return types. As stated above, a C++ destructor for an object is called whenever the object’s lifetime ends. If the object was created as an automatic variable, its lifetime ends and the C++ destructor is called automatically when the object goes out of scope. Because C++ does not have garbage collection, if the object was created with a new statement (dynamically on the heap), then its destructor is called when the delete operator is applied to a pointer to the object. Usually, that operation occurs within another C++ destructor, typically the destructor of a smart pointer object.

In inheritance hierarchies, the declaration of a virtual destructor in the base class ensures that the C++ destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class. Objects that may be deleted in this way need to inherit a virtual destructor.


A C++ destructor should never throw an exception

#include <cstring>
#include <iostream>

class Data {
public:
    Data(): data_(new char[sizeof("Hello, World!")]) {
        std::strcpy(data_, "Hello, World!");
    }

    Data(const Data& other) = delete;             // disable copy construction
    Data& operator=(const Data& other) = delete;  // disable assignment

    ~Data(void) { delete[] data_; }

private:
    friend std::ostream& operator<<(std::ostream& os, const Data& data) {
        os << data.data_;
        return os;
    }

    char* data_;
};

int main() {
    Data data;
    std::cout << data << std::endl;
}

Output:
Hello, World!

Difference between Constructors and Destructors:

Constructors:

A constructor, in programming, allocates the amount of memory to the program that the object needs to take up for as long as it is useful. It essentially constructs a new object in memory…and can maybe set values in the object, do some logic, etc. similar to any ol’ method. This is a pretty standard fixture in most object-oriented languages, such as Java or C++.

  • A Constructor is a special function that gets called automatically when the object of a class is created
  • A constructor is used to initialize the instance of a class.
  • Constructors can have arguments.
  • Constructor overloading can be possible means more than one constructor can be defined in the same class. E.g. default parameterized and copy constructor.
  • A constructor has the same name as the class name.
  • Constructors can be used to dynamically allocate memory.
  • Syntax of the constructor:

class OOP
{
OOP(){}
OOP(argulist){

//Body of Constructor

}
};


Destructors:

A C++ destructor is the opposite, it “frees” the memory used by your program for that object by deleting its values in memory and unallocating it to the application. It destructs (or unconstructs) the object from memory. This is not such a common fixture in object-oriented languages because many higher-level ones have built-in data management schemes, so it automatically destructs objects as needed.

  • Destructor is used to destroy the object that is created in memory.
  • C++ destructor cannot take arguments.
  • C++ destructor overloading is not possible.
  • C++ destructor also has the same name as class name but with (~) tiled operator.
  • C++ destructor releases the memory.
  • Destructor is called when an instance of a class is deleted or released.
  • Syntax of C++ destructor:

class OOP
{

~OOP(){}
};



Virtual Destructors

  • A C++ destructor can be declared to be virtual, and usually should be for a class with a virtual function.
class Shape {

  public:

    // ...

    virtual void draw() = 0;

    virtual ˜Shape();

};

class Circle {

  public:

    // ...

    void draw();

    ˜Circle(); // overrides ˜Shape()

    // ...

};

 

  • The reason we need a virtual destructor is that an object usually manipulated through the interface provided by a base class is often also deleted through that interface like
void user(Shape∗ p)

{

  p−>draw(); // invoke the appropriate draw()

  // ...

  delete p; // invoke the appropriate destructor

}

 

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button