Copy Constructor


Copy Constructor


This constructor is used to initialize the value of an object by copying values of another object
of the same class.

Syntax :

class-name(class-name &object-name)


Example :


#include <iostream.h>
#include <conio.h>

class Account
{
private:

int account_no;
int balance;

public :

Account(int a,int b)
{
account_no=a;
balance=b;
}

Account(Account &m)
{
account_no=m.account_no;
balance=m.balance;
}

void display()
{
cout<< "Account number is : "<< account_no;
cout<< "\nBalance is : " << balance;
}
};

void main()
{
clrscr();

Account acc(121,5000);
Account acc1(acc); //creating a copy of object

cout << "calling with actual object :\n\n";
acc.display();

cout<<"\n\ncalling with copy object:\n\n";
acc1.display();

getch();
}

Output :

0 comments:

Post a Comment