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
The book I'm reading explains the difference in getObject () of code 1 and 2 is that getObject () of code 2 returns a link to the current object instead of a copy (for efficiency reasons).
However, I tested (code 2) as follows:
Tested Code:
Student harry, harry1;
harry.set(123, "ABCD");
harry1 = harry.getObject();
harry1.set(1111,"MMMMMM");
harry.display();
harry1.display(); / Line 2 => displayed: 1111, MMMMMM
I do not understand. If getObject () returns a link, then line 1 in the test code should also display 111, MMMMMM? Because I thought that harry1 should contain the address of the harry object ??? Or am I not understanding something?
source
share