reference - Return the current object (*this) in C++? -
i have 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 code 1 const student& getobject() { return *this; } // no change code 1
as book reading explains difference in getobject() of code 1 , 2 getobject() of code 2 returns reference current object, instead of copy (for efficiency reasons).
however, have tested (code 2) 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 it. if getobject() returns reference, line 1 in tested code should display 111, mmmmmm? because thought harry1 should contain address of harry object??? or misunderstanding something?
although harry.getobject()
reference original object, ruin assignment:
harry1 = harry.getobject();
which performs copy.
instead:
student const& harry1 = harry.getobject();
Comments
Post a Comment