Link to home
Start Free TrialLog in
Avatar of Rothbard
RothbardFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Checking for self assignment

According to many C++ textbooks, you are supposed to check for self assignment when overloading the assignment operator. For instance, in Jesse Liberty's "Teach Yourself C++ in 21 Days" you find the following code to illustrate this

#include <iostream>
using namespace std;

class Cat
{
public:
      Cat();
      Cat(const Cat &);
      ~Cat();
      Cat & operator=(const Cat &);
      int getAge() const {return *itsAge;}
      int getWeight() const {return *itsWeight;}
      void setAge(int age) {*itsAge = age;}
private:
      int * itsAge;
      int * itsWeight;
};

Cat::Cat()
{
      itsAge = new int;
      itsWeight = new int;
      *itsAge = 5;
      *itsWeight = 9;
}

Cat::Cat(const Cat & cat)
{
      itsAge = new int;
      itsWeight = new int;
      *itsAge = cat.getAge();
      *itsWeight = cat.getWeight();
}

Cat::~Cat()
{      
      delete itsAge;
      itsAge = 0;
      delete itsWeight;
      itsWeight = 0;
}

Cat & Cat::operator=(const Cat & cat)
{
      if (this == &cat)    // CHECKS FOR SELF ASSIGNMENT
      {
            return *this;   // RETURNS *this IN CASE THE OBJECT IS ASSIGNED TO ITSELF
      }
      *itsAge = cat.getAge();
      *itsWeight = cat.getWeight();
      return *this;
}

int main()
{
      Cat frisky;
      cout << "frisky's age... " << frisky.getAge() << endl;
      cout << "frisky = frisky; "<< endl;
      frisky = frisky;
      cout << "frisky's age... " << frisky.getAge() << endl;
        return 0;
}

This code works fine. However, if you delete the "self assignment check" bit, it works fine too! So, is it really necessary to check for self assignment?
Thanks.
ASKER CERTIFIED SOLUTION
Avatar of dbkruger
dbkruger

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rothbard

ASKER

Thanks a lot for the explanation!