Define Class Destructor Using the Tilde Operator in C++

  1. Use the Tilde Operator ~ to Declare Class Destructor in C++
  2. Execute Code Before the Class Object Is Destroyed in C++

This article will demonstrate multiple methods about how to define class destructor using the tilde operator in C++.

Use the Tilde Operator ~ to Declare Class Destructor in C++

The destructor is a special member function that handles the deallocation of the class object’s resources. AS opposed to the class constructors, it has only one destructor function for a given class. The class destructor is declared with the same name as the class plus the prefix ~ tilde operator.

In most cases, the class’s destructor is necessary to be defined if there are data members that need to be allocated on dynamic memory. The code should explicitly deallocate these members in the destructor function. The following example demonstrates the CustomString class that is just the wrapper for the std::string. The idea is to define a class with a constructor that allocates memory at a str pointer, which implies that the class requires the destructor to be defined. Note that CustomString has two constructors - one of them is a copy constructor.

#include <iostream>
#include <string>
#include <vector>

using std::cout; using std::endl;
using std::vector; using std::string;

class CustomString {
public:
    explicit CustomString(const string &s = string()):
            str(new string(s)) { }

    CustomString(const CustomString &p):
            str(new string(*p.str)) { }

    ~CustomString() { delete str; }

    string& getString() { return *str; };
private:
    string *str;
};

int main()
{
    CustomString str1("Hello There!");
    CustomString str2(str1);

    cout << "str1: " << str1.getString() << endl;
    cout << "str2: " << str2.getString() << endl << endl;

}

Output:

str1: Hello There!
str2: Hello There!

Execute Code Before the Class Object Is Destroyed in C++

Like the previous method shows, a class destructor is responsible for cleaning up the data members’ memory. Although, the class members are often just the usual data types declared on the program stack. In that case, the destructor may not be declared explicitly by the programmer, but the compiler defines the so-called synthesized destructor.

Generally, the class members are destroyed after the destructor function code is run; thus, we can demonstrate how the StringArray class instance goes out of scope and hence printing to the console the corresponding text.

#include <iostream>
#include <string>
#include <vector>

using std::cout; using std::endl;
using std::vector; using std::string;

class StringArray {
public:
    StringArray(): vec(), init(new int[10]) { };
    ~StringArray() { delete [] init; cout << "printed from destructor" << endl; }

    string getString(int num) {
        if (vec.at(num).c_str()) {
            return vec.at(num);
        } else {
            return string("NULL");
        }
    };

    void addString(const string& s) {
        vec.push_back(s);
    };

    uint64_t getSize() { return vec.size(); };

private:
    vector<string> vec;
    int *init;
};

int main()
{
    StringArray arr;

    arr.addString("Hello there 1");
    arr.addString("Hello there 2");

    cout << "size of arr: " << arr.getSize() << endl;
    cout << "arr[0]: " << arr.getString(0) << endl;
}

Output:

size of arr: 2
arr[0]: Hello there 1
printed from destructor

Related Article - C++ Class

  • Use Private vs Protected Class Members in C++