Return current object (* this) in C ++?

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(); // Line 1 => displayed: 123, ABCD
    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?

+3
source share
5 answers

Although it harry.getObject()is a reference to the source object, you then destroy it by purpose:

harry1 = harry.getObject();

which performs a copy.

Instead

Student const& harry1 = harry.getObject();
+5

, getObject, Student, , 1 ( getObject).

Student& harry1 = harry.GetObject();

harry. , .

+4

, . :

harry1 = harry.getObject()

harry harry1.

+2

harry1 Student, . :

Student harry;
harry.set(123, "ABCD");

Student& harry1 = harry.getObject();
harry1.set(1111,"MMMMMM");
harry.display(); // Line 1 => displayed: 123, ABCD
harry1.display(); / Line 2 => displayed: 1111, MMMMMM
+1

: , :

private:
  Student(Student& xOther);

That way, if you have an unwanted copy, the compiler will detect them (your harry1 is actually a copy). And if you expect to receive copies, you can correctly control how they are executed, which avoids mess with potential pointers or encapsulated objects.

+1
source

All Articles