Deleting Objects with delete - C++ Operator

C++ examples for Operator:delete

Introduction

When you call delete on a pointer to an object on the heap, the object's destructor is called before the memory is released.

Demo Code

                                         
#include <iostream> 
                                         
class SimpleCat /*from   ww  w  . j av a  2 s.c  om*/
{ 
public: 
    SimpleCat(); 
    ~SimpleCat(); 
private: 
    int itsAge; 
}; 
                                         
SimpleCat::SimpleCat() 
{ 
    std::cout << "Constructor called\n"; 
    itsAge = 1; 
} 
                                         
SimpleCat::~SimpleCat() 
{ 
    std::cout << "Destructor called\n"; 
} 
                                         
int main() 
{ 
    std::cout << "SimpleCat Frisky ...\n"; 
    SimpleCat Frisky; 
                                         
    std::cout << "SimpleCat *pRags = new SimpleCat ...\n"; 
    SimpleCat * pRags = new SimpleCat; 
                                         
    std::cout << "delete pRags ...\n"; 
    delete pRags; 
                                         
    std::cout << "Exiting, watch Frisky go ...\n"; 
    return 0; 
}

Result


Related Tutorials