Copy Constructor in C++

constructor is used to copy the value of one object to another object. We used the copy constructor like     “counterrr(counterrr &ob)”. We can declare and initialize an object from another object like “counterrr c2(c1)”.We create two objects that means   counterrr   c1 and c2 .
#include<conio.h>
#include<iostream.h>
class counterrr
{
private:
int coun;
public:
counterrr(int x)     /*constructor with argument*/
{
coun=x;   //value assign to variable count
}
counterrr(counterrr &ob)   //copy constructor
{
coun=ob.coun;
}
void show()
{
cout<<count<<endl;
}
};
void main()
{
counterrr c1(10);   //c1 is the object and 10 is the value given to x variable.
counterrr c2(c1);   //copy constructor
c1.show();       /*function calling by c1 object */
c2.show();   /*function calling by c2 object
getch();
}
copy constructor
Explaination:
In this example we create the constructor(counterrr) with arguments.A reference variable(&ob) has been used as an argument to the copy constructor(counterrr &ob). We cannot pass the arguments by value to a copy constructor.

No comments

Powered by Blogger.