-1

Suppose we have the following piece of C++ code:

struct A
{
    int* a;
    A()
    {
        a = new int(5);
    }

    ~A()
    {
        delete a;
    }
};

struct B
{
    A a;
    int b;

    B()
    {
        a = A();
        b = 10;
    }
};

int main()
{
    B b;

    return 0;
}

When running it, A's destructor gets called twice, but why? From what I understand B's implicit destructor calls all the destructors of B's members, which is fine, but when does the second call to A's destructor happen and why? What's the proper way of handling memory in such cases?

1 Answers1

0

constructors for data members are called in your class's constructor. The default constructor for every member is called before execution reaches the first line in the constructor, unless you explicitly specify a constructor using an initializer list, in which case that constructor is called instead. please debug this and you will understand more , even by hand without a debuger

#include <iostream>
#include <stdlib.h>
struct A
{
    int* a;
    A()
    {
        a = new int(5);
        std::cout<<"A()"<<std::endl;
    }

    ~A()
    {
        std::cout<<"~A()"<<std::endl;
        delete a;
    }
};

struct B
{
    A a; // if you remove this & you remove line 26 there wont be any call to A()
    int b;

    B()
    {
    //    a = A(); // even if this line is removed  there still a call to A() constructor
        b = 10;
    }
};
void pause() // a simple pause function , that we let the system call before exiting to see the output
{
     system("pause");
}
int main()
{
    atexit(pause); // to pause after calling all destructors
    B * b = new B();
    delete b;
    B * b1 = new B();
    delete b1;
    return 0;
}
Hassen Dhia
  • 555
  • 4
  • 11