I’ve got the following code in C++:
#include <iostream>
class Number
{
public:
virtual void foo(){std::cout << "Number foo\n";};
Number (){ std::cout << "Number ctor" << std::endl;}
virtual ~Number(){ std::cout << "Number dtor" << std::endl;}
};
class Complex : public Number
{
public:
virtual void foo(){std::cout << "Complex foo\n";};
Complex (double r=0, double i=0) : _r (r), _i (i)
{ std::cout << "Complex ctor" << std::endl; };
virtual ~Complex(){ std::cout << "Complex dtor" << std::endl;}
private:
double _r,_i;
};
int main()
{
Number *numArr = new Complex [2];
delete [] numArr;
return 0;
}
When the destructors are declared as virtual, the application is quitting with segmentation fault. When it is not declared as virtual, than the Number class destructors are invoked (which is obvious…). But, when the destructors are declared as virtual, AND when i’m removing the doubles in the Complex class, there is no segmentation fault and the destructors are called in the expected order (Complex, Number), So i guess the problem is related to the size of the object, can anyone please give me an explanation?
Thanks,
Amit.
I’m not entirely sure, but this is what I suspect…
I wonder if this is related to the fact that an array of derived classes should not be casted to an array of base classes (they’re not the same, see: http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3): how would
deleteknow the size of the object it is deleting, to adjust the pointer fornumArr[0]andnumArr[1](to find the v-table and passthisto the d-tor)Apparently, the standard explicitly names this as undefined (5.3.5):