Copy Constructor in C++


What is Copy Constructor? Write a sample program.

Note: 

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.

When is copy constructor called?
In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.


Example:

#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 &p2) {x = p2.x; y = p2.y; }
    int getX()            {  return x; }
    int getY()            {  return y; }
};
int main()
{
    Point p1(10, 15); // Normal constructor is called here
    Point p2 = p1; // Copy constructor is called here
    // Let us access values assigned by constructors
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
    return 0;
}

Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15 



8 comments:

  1. ID:201610456
    batch:51st
    link->
    https://ideone.com/3Ilk9d

    ReplyDelete
  2. ID:201610456
    dynamically created
    https://drive.google.com/open?id=12riM_37UYA48LJFws_0j2C6PpEO2UhKd8MJnXpPPRw8

    ReplyDelete
  3. ID : 201620195
    https://www.dropbox.com/s/62aondygevtpjf2/object_copy.cpp?dl=0

    ReplyDelete
  4. ID 201610456
    applying the condition number 1
    "When an object of the class is returned by value."
    link->
    http://ideone.com/8cQ2Rs

    ReplyDelete
  5. 201610058

    https://drive.google.com/open?id=0B7UQyRdu6h2waEZER19KWDdtV1U

    ReplyDelete
  6. ID:201520552
    https://ideone.com/pkhUap

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. ID:201610254

    https://drive.google.com/open?id=0B2uGlLVJ0clcQjJwbXUzYTNHVDQ

    ReplyDelete

Comment Here