Answer to Question #262104 in C++ for Rohit Swain

Question #262104

Demonstrate what are the other area where  copy constructor is called using C++ programme.





1
Expert's answer
2021-11-08T11:25:01-0500
A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype: 






#include<iostream>
using namespace std;
 
class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1) { x = x1; y = y1; }
 
    // Copy constructor
    Point(const Point &p1) {x = p1.x; y = p1.y; }
 
    int getX()            {  return x; }
    int getY()            {  return y; }
};
 
int main()
{
    Point p1(5, 10); 
    Point p2 = p1; 
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
 
    return 0;
}



Copy Constructor may be called in the following cases: 

1. When an object of the class is returned by value. 

2. When an object of the class is passed by value as an argument. 

3. When an object is constructed based on another object of the same class. 


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS