Polygon p1;
p1 = Triangle(temp1, temp2, temp3); // temp 1,2,3 are lengths of sides
is in fact giving you result that is out of your expectation.
What you want to do is something like
Polygon& p1;
Triangle t(temp1, temp2, temp3);
p1 = t;
or
Polygon* p1 = new Triangle(temp1, temp2, temp3);
The problem in
p1 = Triangle(temp1, temp2, temp3);
is not only the Triangle object is temporary and destroyed right after the statement, but, more seriously, the copy from the Triangle object to p1 which is the Polygon, is only copying as is a Polygon. Therefore, the "copied" p1 is not containing any com/tag/information">information of Triangle.
Another problem is the way you write the destructor. Destructor in C++ is automatically chained (I think you are coming from Java com/tag/background">background which we need to explicitly invoke super class' finalizer)
Rectangle::~Rectangle(void)
{
Polygon::~Polygon(); // can be removed
}
Therefore you shouldn't call Polygon's destructor.
Another thing about destructor is, if your class is supposed to be inherited (your Polygon is a good example), you should declare your destructor to be virtual. For the reason behind, search for "virtual destructor".
manpreet Best Answer 2 years ago
I have thous objects:
And I have an inheriting class of
Polygon
calledTriangle
, and I try to do:But for some reason the destructor for
Triangle
is called at the end of construction.Then it runs the destructor for
Polygon
a second time.so after the code ends this is what the debugger says about
p1
(n
is number of sides):Questions:
Triangle
andPolygon
's destructor are called?EDIT: as requested:
Also, thanks for the explanation why it ran
~Polygon
, will take into account.