close

 

This example shows that what is the Constructor, Destructor, Copy constructor

and Assignment constructor.

 

Code : 


#include <iostream>
using namespace std; class Point { public: Point(); Point(int x, int y); ~Point(); Point(const Point& pt); Point& operator=(const Point& pt); private: int x; int y; }; // Constructor Point::Point() { this->x = 0; this->y = 0; cout << "Constructor : x = " << this->x << " y = " << this->y << "\n"; } // Constructor Point::Point(int x, int y) { this->x = x; this->y = y; cout << "Constructor : x = " << this->x << " y = " << this->y << "\n"; } // Destructor Point::~Point() { this->x = this->x - 1; this->y = this->y - 1; cout << "Distructor : x = " << this->x << " y = " << this->y << "\n"; } // Copy Constructor Point::Point(const Point& pt) { this->x = pt.x + 10; this->y = pt.y + 10; cout << "Copy Constructor : x = " << this->x << " y = " << this->y << "\n"; } // Assignment Constructor Point& Point::operator=(const Point& pt) { this->x = pt.x + 20; this->y = pt.y + 20; cout << "Assignment Constructor : x = " << this->x << " y = " << this->y << "\n"; } int main() { Point *pt1 = new Point(5, 6); // calls constructor Point pt2( *pt1 ); // calls copy constructor Point pt3; pt3 = pt2; // calls assignment constructor delete pt1; // calls destructor cout << "main code end\n"; return 0; }

 

Output :


Constructor : x = 5 y = 6 // Point *pt1 = new Point(5, 6); Copy Constructor : x = 15 y = 16 // Point pt2( *pt1 ); Constructor : x = 0 y = 0 // Point pt3; Assignment Constructor : x = 35 y = 36 // pt3 = pt2; Distructor : x = 4 y = 5 // delete pt1; main code end Distructor : x = 34 y = 35 // release pt3 Distructor : x = 14 y = 15 // release pt2

 

 

arrow
arrow

    Cuby 56 發表在 痞客邦 留言(0) 人氣()