Skip to main content

Posts

Showing posts with the label ConstructorsDestructors

Destructor

Similar to constructor, a class has another special member function called destructor . Destructor cleans up the object.   When an object goes out of scope, the destructor is automatically called. Destructor is also called when the pointer to the object is released using delete operator. Destructor has a same name as class and is preceded by tilde (~) symbol.   Class A has a destructor ~A()   Destructor should be used to clean up the object -  release memory and other resources, close files, stop threads etc. #include <iostream> using namespace std; class Arr { int * elements; int len; public: Arr( int len =5 ); ~ Arr(); //destructor int & operator []( int index); }; Arr :: Arr( int len) { elements = new int [len]; } Arr ::~ Arr() { delete []elements; } int & Arr :: operator []( int index) { return elements[index]; } int main() { Arr obj( 10 ); for ( int i =0 ;i <10 ;i ++ ) obj[i] = i *...