Unexpected C++ program result
Mattia Jona-Lasinio
mattia.jona@gmail.com
Tue Feb 7 17:21:00 GMT 2012
Hi list, I hope it is the right place to post this question.
BEGIN OF CODE
-------------------------
#include <iostream>
class Base
{
public:
Base() {std::cout << "Build Base" << std::endl;};
virtual ~Base() {std::cout << "Destroy Base" << std::endl;};
};
class Derived1 : virtual public Base
{
public:
Derived1() {std::cout << "Build Derived1" << std::endl;};
~Derived1() {std::cout << "Destroy Derived1" << std::endl;};
};
class Derived2 : virtual public Base
{
public:
Derived2() {std::cout << "Build Derived2" << std::endl;};
~Derived2() {std::cout << "Destroy Derived2" << std::endl;};
};
class Final : public Derived1, public Derived2
{
public:
Final() {std::cout << "Build Final" << std::endl;};
~Final() {std::cout << "Destroy Final" << std::endl;};
};
int main()
{
Base *a = new Final[3];
delete[] a;
return (0);
}
-----------------------
END OF CODE
The above program compiled with g++ 4.3.2 gives the following output.
Build Base
Build Derived1
Build Derived2
Build Final
Build Base
Build Derived1
Build Derived2
Build Final
Build Base
Build Derived1
Build Derived2
Build Final
Destroy Final
Destroy Derived2
Destroy Derived1
Destroy Base
Destroy Final
Destroy Derived2
Destroy Derived1
Destroy Base
Destroy Base
The program builds three complete objects of type Final, Derived1,
Derived2 and Base. However when it comes to destroying these objects
it only destroys two of them
It is clear that if in main() we write
Final *a = new Final[3];
everything works fine.
The program wants to test the C++ feature that pointers to a derived
class can be assigned consistently to a pointer variable to the base
class. This does not seem to be the case with g++. Is it the intended
behavior?
I also checked with the Intel icc 11.0 compiler that gives the result
Build Base
Build Derived1
Build Derived2
Build Final
Build Base
Build Derived1
Build Derived2
Build Final
Build Base
Build Derived1
Build Derived2
Build Final
Destroy Base
Destroy Base
Destroy Base
Here the objects are built in the correct way but, even worse, all of
them are not destroyed at all except for the Base object.
Thanks for your comments and suggestions.
Mattia
More information about the Gcc-help
mailing list