G
gurry
Suppose there's a class A. There's another class called B which looks
like this:
class B {
private:
A a;
public :
B() { a.~A() }
}
Notice that B has a member 'a' which is an instance of class A. Also
notice that the default constructor of B calls the destructor of 'a'.
Let's now use class B in a main() block:
void main() {
B obj;
}
My question is: when this main() is run, what happens?
Well, I myself have compiled and run this code and I found that the
destructor of 'a' is called twice: first when 'obj' is constructed
(because class B's constructor calls 'a's destructor explicitly) and
second time when the control exits the main() block and 'obj' is
destroyed by calling class B's destructor.
Now if 'a' has already been destroyed in class B's constructor, how can
'a''s destructor be called again through class B's destructor? Does
that mean that even after 'a's destructor is called in class B's
construtor, it isn't actually destroyed?
My motive for this experiment is to know what to do when you want to
throw exceptions from a constructor of any class and you want to
properly destroy all its member objects before the exception is thrown.
Is calling members' destructors like I did above a right way to achieve
this?
Thanks in advance,
Gurry
like this:
class B {
private:
A a;
public :
B() { a.~A() }
}
Notice that B has a member 'a' which is an instance of class A. Also
notice that the default constructor of B calls the destructor of 'a'.
Let's now use class B in a main() block:
void main() {
B obj;
}
My question is: when this main() is run, what happens?
Well, I myself have compiled and run this code and I found that the
destructor of 'a' is called twice: first when 'obj' is constructed
(because class B's constructor calls 'a's destructor explicitly) and
second time when the control exits the main() block and 'obj' is
destroyed by calling class B's destructor.
Now if 'a' has already been destroyed in class B's constructor, how can
'a''s destructor be called again through class B's destructor? Does
that mean that even after 'a's destructor is called in class B's
construtor, it isn't actually destroyed?
My motive for this experiment is to know what to do when you want to
throw exceptions from a constructor of any class and you want to
properly destroy all its member objects before the exception is thrown.
Is calling members' destructors like I did above a right way to achieve
this?
Thanks in advance,
Gurry