I have two classes class A and class B
class A let class B be a friend
When I call the destructor of the class B I also call the destructor
of the class A, but the constructor is being called twice. any suggestion?
What is being called twice - the destructor or constructor - your thread title says one thing, but
your actual question says another.
If the destructor is being called twice on the same object:
One possibility is that you are explicitly calling the destructor
on a variable, but then when the variable goes out of scope the compiler is going to call the
destructor anyway - so you will get a double call of the destructor
which depending on the class design may or maynot be a fatal mistake.
Examle:
1 2 3 4 5 6 7
void some_function()
{
T t;
t.~T(); //explicit call of destructor
} //t goes out of scope and compiler will call destructor again
class a
{
public:
a () {};
~a () {};
}
class b : public a
{
public:
b () {};
~b () {};
a classvar;
}
which actually compiles as this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class a
{
public:
a () {};
~a () {};
}
class b
{
a () { b; };
b () {};
~a () {};
~b () { ~a; };
a classvar;
}
so if you get whats happening there, class b, is class a with extra stuff... so when you call b varname; it actually calls a(), then it calls b()... and when u call delete bvar it actually calls delete b, which at the end calls delete a
if you have a class that extends another class, it automatically calls that classes constructors and destructors with its own in this order: a, b, ~b, ~a so if you delete b it calls both destructors, if you want to call only 1 destructor dont extend the other class but have members in class b of type class a
It's because you're explicitly calling the destructor - an unbelievably stupid move. Never, ever call a destructor explicitly unless you've allocated the object with placement new.
Here's what's happening.
b's destructor is called, which calls t's destructor. When the destructor is finished, the destructor of each data member is called implicitly; thus, t's destructor is called twice.