In this C++ example, a class C has a default constructor, a copy constructor and an assignment operator:
struct C {
C();
C(const C& c);
C& operator=(const C& c);
};
The implementation is as follows with some output for tracking the objects. I added some example addresses in comments on the lines as reference to the main program below.
#include "C.h"
#include <iostream>
using namespace std;
C::C() {
cout << "Standard constructor." << endl;
}
C::C(const C& c) {
cout << "Copy constructor." << endl;
}
C& C::operator=(const C& c) {
cout << "Address of reference argument: &c = " << &c << endl; // F9B4
cout << "Address of this: &*this = " << &*this << endl; // F8D4
return *this;
}
I'll be using a factory method that returns anonymous objects:
C foo() {
return C();
}
Now in the following program, I create a named object c (see (1)) and create an anonymous object (2) which I assign to c (3). I expected that c then has the address of the anonymous object after the assignment.
int main()
{
C c; // (1)
cout << "Address of initial c from main: &c = " << &c << endl; // F8D4
c=foo(); // (2) and (3)
cout << "Address of initial c from main after assignment: &c = " << &c << endl; // Expected F9B4 but is F8D4
}