c++ - object goes out of scope before = operation -


i have thous objects:

polygon p1, p2; 

and have inheriting class of polygon called triangle, , try do:

p1 = triangle(temp1, temp2, temp3); // temp 1,2,3 lengths of sides 

but reason destructor triangle called @ end of construction.

rectangle::~rectangle(void) {     polygon::~polygon(); }  polygon::~polygon(void) {     if (sides != null)     {         delete [] sides;         sides = null;     } } 

then runs destructor polygon second time.

so after code ends debugger says p1( n number of sides):

p1  {n=3 sides=0x0062c070 {-17891602} } polygon 

questions:

  • why call destructor?
  • why both triangle , polygon's destructor called?
  • how can fixed?

edit: requested:

/*returns true if polygons , b: (a) each side on polygon there equal side on polygon b (b) number of sides in polygons , b equal (c) sum of sides of equals sum of sides of b */ bool polygon::operator==(const polygon& p) const {     if (n != p.n)         return false;     if(circumference() != p.circumference())         return false;     (int i=0; < n; i++)         if (!doessidehasequal(sides[i], p, n))             return false;     return true; } 

also, explanation why ran ~polygon, take account.

polygon p1;  p1 = triangle(temp1, temp2, temp3); // temp 1,2,3 lengths of sides 

is in fact giving result out of expectation.

what want

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 triangle object temporary , destroyed right after statement, but, more seriously, copy triangle object p1 polygon, copying polygon. therefore, "copied" p1 not containing information of triangle.


another problem way write destructor. destructor in c++ automatically chained (i think coming java background need explicitly invoke super class' finalizer)

rectangle::~rectangle(void) {     polygon::~polygon();  // can removed } 

therefore shouldn't call polygon's destructor.

another thing destructor is, if class supposed inherited (your polygon example), should declare destructor virtual. reason behind, search "virtual destructor".


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -