serkan sendur 821 Postaholic Banned

if the object is created on the stack, the destructor is called automatically when the object is out of its scope. if the object is created on the heap using new operator, the destructor is fired explicity by using delete keyword.

i created an example to demonstrate both cases:

#include <iostream>
#include <string>
using namespace std;
class deneme
{
  public:
    deneme();
    ~deneme();
};

deneme::deneme()
{
  cout<< "constructor fired" << endl;
  
}
deneme::~deneme()
{
  cout << "destructor fired" << endl;
}
void CreateInstance()
{
  deneme mydeneme;

}
void CreateInstanceUsingNew()
{
  deneme * mydeneme = new deneme();
  delete mydeneme;
}
int main()
{
    CreateInstance();
    CreateInstanceUsingNew();
    return 0;
}

when you run the code the output is as follows:

constructor fired
destructor fired
constructor fired
destructor fired

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.