Gitlab will be upgraded to new release 13.9.6 on Monday 19th April at 22:00 until 23:00.

Commit 49f35bdd authored by Hans Buchmann's avatar Hans Buchmann

copy constructor

 numer of constructor calls == numer of destructor calls
parent 5a6815e6
...@@ -13,7 +13,8 @@ class Point ...@@ -13,7 +13,8 @@ class Point
public: public:
Point(double x,double y); //constructor x/y position in the plane Point(double x,double y); //constructor x/y position in the plane
//non default constructor //non default constructor
~Point(); //destructor no parameters Point(const Point& other); //copy constructor
~Point(); //destructor no parameters
double distance(Point other); double distance(Point other);
static double distance(Point p,Point q); static double distance(Point p,Point q);
...@@ -32,6 +33,12 @@ Point::Point(double x,double y) //x,y parameter ...@@ -32,6 +33,12 @@ Point::Point(double x,double y) //x,y parameter
std::cout<<"constructor of Point "<<xc<<","<<yc<<"\n"; std::cout<<"constructor of Point "<<xc<<","<<yc<<"\n";
} }
Point::Point(const Point& other)
:xc(other.xc),yc(other.yc)
{
std::cout<<"copy constructor of Point "<<xc<<","<<yc<<"\n";
}
Point::~Point() Point::~Point()
{ {
std::cout<<"destructor of Point "<<xc<<","<<yc<<"\n"; std::cout<<"destructor of Point "<<xc<<","<<yc<<"\n";
...@@ -47,10 +54,30 @@ double Point::distance(Point other) //is a member of Point ...@@ -47,10 +54,30 @@ double Point::distance(Point other) //is a member of Point
{ {
return std::hypot(xc-other.xc, return std::hypot(xc-other.xc,
yc-other.yc); yc-other.yc);
} } //destructor of other
//---------------------------------------------- Line //---------------------------------------------- Line
/*
constructor of Point 3,4 p
constructor of Point 6,8 q
destructor of Point 6,8 other
d=5
destructor of Point 6,8 q
destructor of Point 3,4 p
*/
/* with own copy constructor
constructor of Point 3,4 p
constructor of Point 6,8 q
copy constructor of Point 6,8 other
destructor of Point 6,8 other
d=5
destructor of Point 6,8 q
destructor of Point 3,4 p
*/
int main(int argc,char**args) int main(int argc,char**args)
{ {
Point p(3,4); Point p(3,4);
...@@ -58,8 +85,7 @@ int main(int argc,char**args) ...@@ -58,8 +85,7 @@ int main(int argc,char**args)
/* /*
distance (3,4) -> (6,8) = sqrt(3*3+4*4)=sqrt(25)=5 distance (3,4) -> (6,8) = sqrt(3*3+4*4)=sqrt(25)=5
*/ */
auto d0=Point::distance(p,q); //with static auto d1=p.distance(q);
auto d1=p.distance(q); //non static
std::cout<<"d="<<d1<<"\n"; std::cout<<"d="<<d1<<"\n";
return 0; return 0;
} }
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment