Copy Constructor in C++
A copy constructor is a member function which initializes an object using another object of the same class.
A copy constructor has the following general function prototype:
classname (const classname & old_obj)
// Cpp program to demonstrate Copy constructor.
A copy constructor is a member function which initializes an object using another object of the same class.
A copy constructor has the following general function prototype:
classname (const classname & old_obj)
// Cpp program to demonstrate Copy constructor.
#include<iostream>
using namespace std;
class point
{
private:
int x,y;
public:
point() // default constructor
{
x=0;y=0;
}
point (int x1, int y1) // parameterized constructor
{
x=x1; y=y1;
}
// Copy Constructor
point(const point &p2)
{
x=p2.x;
y=p2.y;
}
void showdata()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
point p1;
point p2(10,15); // normal constructor called here
point p3(p2); // copy constructor called here p3=p2
p1.showdata();
p2.showdata();
p3.showdata();
return 0;
}
using namespace std;
class point
{
private:
int x,y;
public:
point() // default constructor
{
x=0;y=0;
}
point (int x1, int y1) // parameterized constructor
{
x=x1; y=y1;
}
// Copy Constructor
point(const point &p2)
{
x=p2.x;
y=p2.y;
}
void showdata()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
point p1;
point p2(10,15); // normal constructor called here
point p3(p2); // copy constructor called here p3=p2
p1.showdata();
p2.showdata();
p3.showdata();
return 0;
}
OUTPUT:
0 0
10 15
10 15
0 0
10 15
10 15