Copy Constructor in c++ Programming

Copy Constructor in c++ Programming

Copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
Copy Constructor is used :
To initialize one object from another of the same type.
To copy an object to pass it as an argument to a function.
To copy an object to return it from a function.

SYNTAX:
classname (const classname &obj) {
   // body of constructor
}

Simple Example of Copy Constructor:

//Copy constructor:
#include<iostream>
#include<conio.h>
using namespace std;
class hike{
int a;
public:
hike()
{
a;
}
hike(int x)
{
a=x;
}
hike(hike &obj)
{
a=obj.a;
}
void display()
{
cout<<"\n value is :"<<a;
}
};
int main()
{
hike t1(10);
hike t2(t1);
hike t3(t2);
t1.display();
t2.display();
t3.display();


}

OUTPUT:


No comments

Powered by Blogger.