Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

About returning a reference

Hi, I am going through Jesse Liberty's "Teach Yourself C++ in 21 Days" and found the following program with an example of overloaded assignment operator:

#include <iostream>
using namespace std;

class CAT
      int GetAge() const {return *catAge;}
      int GetWeight() const {return *catWeight;}
      void SetAge(int age) {*catAge = age;}
      CAT &   operator= (const CAT &);

      int *catAge;
      int *catWeight;

      catAge = new int;
      catWeight = new int;
      *catAge = 5;
      *catWeight = 8;

      delete catAge;
      catAge = 0;
      delete catWeight;
      catWeight = 0;

CAT &  CAT::operator=(const CAT & rhs)
      if (this == &rhs)
            return *this;
            *catAge = rhs.GetAge();
            *catWeight = rhs.GetWeight();
            return *this;

int main()
      CAT *Cat1 = new CAT;
      cout << "Cat1's age: " << Cat1->GetAge() << endl;
      cout << "Setting Cat1's age to 6..." << endl;
      CAT *Cat2 = new CAT;
      cout << "Cat2's age: " << Cat2->GetAge() << endl;
      cout << "Now setting Cat2 equal to Cat1... \n";
      Cat2 = Cat1;
      cout << "Cat2's age now: " << Cat2->GetAge() << endl;
        return 0;

I have a simple question: why does the overloaded assignment operator return a reference to a CAT object rather than a CAT object? Does it make any difference if you change it to return a CAT object instead? I tried changing it and couldn't see any difference in the output; after all all it should do is make a "shallow copy" of Cat1 and point it to the same area in the free store.
  • 2
1 Solution
It is necessary for writing assignments like:

Cat1 = Cat2 = Cat3;

It is executed by the following way:

Cat1 = (Cat2 = Cat3);

This means, Cat3 value is assigned to Cat2; result of this assignment (Cat2&) is assigned to Cat1.
For example, stream << operators always return stream reference:
ostream& operator<<(int).
If operator << returns void, it is possible to write:
cout << n;
but line
cout << n << endl
is not compiled.

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now