Functions and Objects

Destructor in C++

The destructor is a method called when the object is destroyed.


Syntax
//within a class
public:
    ~className(void) {
        //code to run on object deletion
    }

Notes

Often used to free pointers associated with the object, or send a message.


Example
using namespace std;

class City {
public:
    string cityName;
    int population;
    City(String cityName, int population) { 
            this->cityName = cityName;
            this->population = population;
     }
    ~City() {
        cout << "This city is being destroyed" << endl;
     }
}

< Friend Class   |   String Variables >

© 2019 SyntaxDB. All Rights Reserved.