I have the following code:
Code 1
class Student {
int no;
char grade[M+1];
public:
Student() {
no = 0;
grade[0] = '\0';
}
void set(int n, const char* g) {
no = n;
strcpy(grade, g);
}
const Student getObject() {
return *this;
}
void display() const {
cout << no << ", " << grade << endl;
}
};
Code 2:
// no change from code 1
const Student& getObject() {
return *this;
}
// no change from code 1
As the book I am reading explains the difference in the getObject() of the code 1 and 2 is that the getObject() of code 2 returns a reference to the current object, instead of a copy (for efficiency reasons).
However, I have tested (code 2) as follows:
Tested code:
Student harry, harry1;
harry.set(123, "ABCD");
harry1 = harry.getObject();
harry1.set(1111,"MMMMMM");
harry.display(); // Line 1 => displayed: 123, ABCD
harry1.display(); / Line 2 => displayed: 1111, MMMMMM
I dont get it. If the getObject() returns a reference, then Line 1 in the tested code should also display 111, MMMMMM? Because I thought that harry1 should contain the address of harry object???
Or am I misunderstanding something?
Although
harry.getObject()is a reference to the original object, you then ruin it with the assignment:which performs a copy.
Instead: