Showing posts with label Assignment Operator. Show all posts
Showing posts with label Assignment Operator. Show all posts

Thursday, 18 June 2009

Copy Constructor and Assignment Operator

This example shows the Copy Constructor and the Assignment Operator. In the example, I have just relied on the Default Copy Constructor and the Default Assignment Operator. For a complex class, the default may not be a good option and they will have to be explicitly written.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
A {
public
:
int
x,y;
};


int
main()
{

A a;
a.x = 11;
a.y = 2222;

A a2(a); //Default Copy constructor called
//Copies a paramaters to a2
cout<<"a2 variables are: a2.x = "<<a2.x<<" and a2.y = "<<a2.y<<endl;

A a3;
a3 = a; //Default Assignment Operator called
//Copies a paramaters to a3
cout<<"a3 variables are: a3.x = "<<a3.x<<" and a3.y = "<<a3.y<<endl;

return
0;
}



The output is as follows: