Salt_Peter
10/15/2008 2:15:00 PM
On Oct 15, 8:59 am, george.p...@gmail.com wrote:
> On Oct 15, 3:14 am, Salt_Peter <pj_h...@yahoo.com> wrote:
>
>
>
> > On Oct 15, 12:24 am, george.p...@gmail.com wrote:
>
> > > On Oct 15, 12:20 am, cron...@gmail.com wrote:
>
> > > > If you have:
>
> > > > #include <iostream>
>
> > > > using namespace std;
>
> > > > class Base
> > > > {
> > > > public:
> > > > ~Base()
> > > > {
> > > > cout << "~Base()" << endl;
> > > > }
>
> > > > int x;
>
> > > > };
>
> > > > class Derived : public Base
> > > > {
> > > > public:
> > > > ~Derived()
> > > > {
> > > > cout << "~Derived()" << endl;
> > > > }
>
> > > > int y;
> > > > int z;
>
> > > > };
>
> > > > int main()
> > > > {
> > > > Base* b = new Derived;
> > > > delete b;
>
> > > > }
>
> > > > Only ~Base() is called, which is expected since it is not virtual.
> > > > However, when delete is called, will it free the memory allocated for
> > > > the variables y and z?
>
> > > Yes
>
> > No, absolutely not
> > this test case proves it, ~Derived() is not invoked.
>
> Automatic members will be deallocated outside of the user-provided
> destructor similar to allocating deallocating by malloc/free. If y, z
> would be a pointers allocated within the lifetime of Derived object
> and deallocated by Derived::~Derived(), then you will get a memory
> leak.
>
> Regards, George
The members are not automatic:
#include <iostream>
class Member
{
public:
~Member()
{
std::cout << "~Member()" << std::endl;
}
};
class Base
{
Member m;
public:
~Base()
{
std::cout << "~Base()" << std::endl;
}
};
class Derived : public Base
{
Member m;
public:
~Derived()
{
std::cout << "~Derived()" << std::endl;
}
};
int main()
{
Base* p_b = new Derived;
delete p_b;
}
output:
~Base()
~Member()
With virtual ~dtor:
~Derived()
~Member()
~Base()
~Member()