Copy constructor example (important)

#include <iostream>
using namespace std;
class A
{
public:
	A(int a = 1, int b = 2) //constructor with default parameter values
	{
		x = a;
		y = b;
	}
	A(A& obj) //copy constructor
	{
		x = obj.x;
		y = obj.y;
		cout << "copy_constructor called." << endl;
	}
	~A() {
	
		cout << "destructor called.\n";
	}
	int Getx()
	{
		return x;
	}
	int Gety ()
	{
		return y;
	}
	A& operator=(A obj) {
		std::cout << "assignment operator called." << endl;
		x = obj.x, y = obj.y;
		std::cout << "obj address :" << &obj << std::endl;
		return *this;
	}
private:
	int x, y;
};
A& fun()
{
	A  * a  = new A(15, 30);
	std::cout << "pointer address :" << a << std::endl;
	return *a;
}
void main()
{
	A b;
	cout << b.Getx() << ", " << b.Gety() << endl;
	b = fun();
	cout << b.Getx() << ", " << b.Gety() << endl;
	std::cout << "b address :" << &b << std::endl;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312191&siteId=291194637