Search code examples
c++oopinitializationcopy-constructor

How can I implement a copy constructor to this program?


#include <iostream>

using namespace std;

class Point{
private: 
  int x, y;
public:
  Point(int x, int y) { this->x = x; this->y = y } 
  Point(const Point &p) { x = p.x; y = p.y; }

  int getX(void) { return x; }
  int getY(void) { return y; }
};

int main(){
    Point myPt(1,2);
    Point myPt2 = myPt;

    cout << myPt.getX() << " " << myPt.getY() << endl;
    cout << myPt2.getX() << " " << myPt2.getY() << endl;
    
  return 0;
}

I want to set myPt2 to a different value while keeping myPt values the same, even after setting myPt2 equal to myPt (redefinition error when I do this). For example, Point myPt(1,2); Point myPt2 = myPt; ....print output, then set myPt2(5, 5) and print statements again: I want the output 1 2 \n5 5.


Solution

  • If I'm understanding you correctly, you are looking for a way to make below code work:
    int main(){
        Point myPt(1,2);
        Point myPt2 = myPt;
        myPt2(5, 5);
    
        cout << myPt.getX() << " " << myPt.getY() << endl;    // prints "1 2"
        cout << myPt2.getX() << " " << myPt2.getY() << endl;  // prints "5 5"
    }
    

    To allow the syntaxmyPt2(5, 5), you must overload the call operator, operator(), to accept 2 integers:

    class Point {
      ⋮
    public:
      void operator()(int x, int y)
      {
          this->x = x; this->y = y;
      }
      ⋮
    };
    


    However, I strongly suggest to not go this approach. Instead, when you want to reassign values to myPt2, you really should be calling the copy assignment operator using the following syntax:

    myPt2 = Point(5, 5);
    

    To write your own copy assignment operator, it would be something like:

    class Point {
      ⋮
    public:
      Point& operator=(const Point &p)
      {
          x = p.x;
          y = p.y;
          return *this;
      }
      ⋮
    };
    

    In fact, based on what your class do, you really don't need to write either copy constructor or the copy assignment operator. This is all you need:

    class Point{
    private: 
      int x, y;
    public:
      Point(int x, int y) { this->x = x; this->y = y; } 
    
      int getX(void) { return x; }
      int getY(void) { return y; }
    };
    

    Any kind of copy construction will be done automatically. You really only need to define your own copy constructors if you either have non-copyable members, or if you are looking for some custom copy behavior, such as doing deep copying a pointer.