locked
Regarding Copy Constructor RRS feed

  • Question

  • Here is a sample code which have copy constructor.

    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();
    }

    If run this code, the result is like following.

    And without copy constructor of the Point class, the result is the same.

    Then, why we need copy constructor in this case?

    Friday, April 10, 2020 2:41 AM

Answers

  • When you don't provide a copy constructor, the compiler generates one automatically. This implicitly-defined copy constructor performs member-wise copy; meaning, it just copy-constructs each base class and member from the corresponding base class and member of its argument.

    Your explicitly defined copy constructor happens to do the exact same thing; that's why adding it makes no difference. You only need a user-defined copy constructor when it has to do something more complicated than a member-wise copy.

    The above is also true of a move constructor, copy assignment operator, and move assignment operator.


    Igor Tandetnik

    • Marked as answer by Jeff0803 Sunday, April 12, 2020 12:48 AM
    Friday, April 10, 2020 4:14 AM