0

This is my code:

#include <iostream>
using namespace std;

class A
{
    int i;

public:
    A(int v) : i(v) { }

    A(const A& r) : i(r.i) {
        cout << "Copy constructor" << endl;
    }

    A operator=(const A& r) {
        cout << "Assignment function" << endl;
        return r;
    }

    void show() {
        cout << i << endl;
    }
};

int main()
{
    A a(1);
    A b(2);
    a = b;
    a.show();
    return 0;
}

Value of b is 2 and value of a is 1. In 'main', b is copied into a and this the output I get:

Assignment function
Copy constructor

This is understandable, but the output for a.show() comes out be 1. I can't understand this. How? Because b is copied into a using the copy constructor so shouldn't a.i have the value of b.i?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
svetaketu
  • 269
  • 1
  • 10
  • 2
    STRONG RECOMMENDATION: please review this thread: [C++: What is the Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). It has a very useful discussion about what it means to "copy" an object, about the distinction between "copy constructor" and "assignment operator" and how/when/why you want to apply them. – paulsm4 Aug 29 '15 at 22:57

3 Answers3

6

b is copied into a using the assignment operator, not the copy constructor. And your assignment operator doesn't assign i, so a.i keeps its original value.

The copy constructor you are seeing is for the return value of operator=. It is more customary to return the left-hand-side by reference, not the right-hand-side by value:

A& operator=(const A& r) {
    cout << "Assignment function" << endl;
    i = r.i;
    return *this;
}
user1937198
  • 4,987
  • 4
  • 20
  • 31
aschepler
  • 70,891
  • 9
  • 107
  • 161
2

When you define the assignment operator you have to do all of the work to copy the data.

A operator=(const A& r) {
    cout << "Assignment function" << endl;
    i = r.i;
    return r;
}

so a = b is calling your assignment operator (obviously, hence your output). But right now it isn't copying anything.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Michael Albers
  • 3,721
  • 3
  • 21
  • 32
1

The assignment operator doesn't do anything to the "assigned to" object. The copy constructor call you see reported is from the creation of the assignment return value.

Your copy assignment should probably look loke this:

A& A::operator= (A const& other) {
    // output
    this->i = other.i;
    return *this;
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380