Thread: Assignment operator overloading

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    5

    Assignment operator overloading

    Hello,

    I am having a hard time understanding the assignment operator overloading in a class that has a pointer as its member attribute. My question is: why does it make a memory leak if you do not delete the pointer before reassigning the value of the right hand side object? For example, there is a class called Number that has a pointer, itsNum, to an integer that is dynamically allocated (just as an example). Here is the code for assignment operator:

    Code:
    Number& Number::operator=(const Number& rhs)
    {
        if (this != &rhs)
        {
            delete itsNum;
            itsNum = new int;
            *itsNum = *(rhs.itsNum);
        }
        
        return *this;
    }
    Also, another question is if pointers of *this and rhs point to the same address (even though two objects are distinct), doesn't deleting itsNum create a problem?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Menu
    By Krush in forum C Programming
    Replies: 17
    Last Post: 09-01-2009, 02:34 AM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Help with a pretty big C++ assignment
    By wakestudent988 in forum C++ Programming
    Replies: 1
    Last Post: 10-30-2006, 09:46 PM
  5. Replies: 1
    Last Post: 10-27-2006, 01:21 PM