Question

#include <iostream>

using namespace std;

class Base
{
    public:
        Base ( )
        {
            cout << "Inside Base constructor" << endl;
        }

        ~Base ( )
        {
            cout << "Inside Base destructor" << endl;
        }

};

class Derived : public Base
{
    public:    
        Derived  ( )
        {
        cout << "Inside Derived constructor" << endl;
        }

        ~Derived ( )
        {
            cout << "Inside Derived destructor" << endl;
        }
};

class Derived2 : public Base
{
    public:
        static void bogus(Derived2* d)
        {
            cout << "bogus" << endl;
        }

        Derived2  ( )
        {
            cout << "Inside Derived2 constructor" << endl;
        }

        ~Derived2 ( )
        {
            cout << "Inside Derived2 destructor" << endl;
        }
};

int main( )
{
    Derived y;
    Derived2::bogus( new Derived2 ());

    return 0;
}

-

>Inside Base constructor
>Inside Derived constructor
>Inside Base constructor
>Inside Derived2 constructor
>bogus
>Inside Derived destructor
>Inside Base destructor
>Press <RETURN> to close this window...

I was testing some stuff and found this weird behavior. How come the destructor is not called when we create an object inside the parameter field? Is there any solution, is it even needed, is there memory leak?

Was it helpful?

Solution

First of all - when you're making classes derive from one another, you should make sure the destructors are virtual. If you don't, you may have memory leaks when the deriving classes have additional members:

virtual ~Base ( )
{
  cout << "Inside Base destructor" << endl;
}

Secondly - when you allocate memory using new, the destructor won't be called on the created object, untill you manually delete it with delete:

int main( )
{
  Derived y;
  Derived2 *ptr = new Derived2();
  Derived2::bogus(ptr);
  delete ptr;
  return 0;
}

If you're unsure on when to delete the object, use std::shared_ptr or delete it inside the destructor of the class taking it as the parameter. Note that shared_ptr is available only for C++11, if you're using an older version (like still many people are), try using the boost library.

OTHER TIPS

You do not create an object inside the parameter field. You create an object on the free store (aka heap). You have to call delete to destroy it. For everey new there has to be a delete. There is a memory leak!

Whatever created by new needs to be delete. Here you are creating temp object. Try to create before passing to function. Also make base destructor virtual.

int main( )
{

  Derived y;
  Derived2 *d2 = new Derived2();
  Derived2::bogus( d2);

  delete d2;

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top