Thread: default implementation of assignment operator

  1. #1
    Registered User
    Join Date
    May 2006

    default implementation of assignment operator

    Hello everyone,

    I am wondering the default implementation of assignment operator (e.g. when we do not implement assignment operator in user defined class, what will be returned? temporary object? reference or const reference? deep copy or shallow copy is used in default assignment operator?)? I have the C++ Programming Book at hand, but can not find it from Index page.

    thanks in advance,

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Toronto, ON
    It's mainly necessary when your object contains pointers, since you probably want to create a copy of the object being pointed to, not just the pointer.

  3. #3
    Captain - Lover of the C
    Join Date
    May 2005
    I think (not positive) that it works like:
    MyClass MyClass::operator = (const MyClass& right)
        value1 = right.value1;
        value2 = right.value2;
        value3 = right.value3;
        // etc...
        return this;
    That may not be totally correct but I think I got the main idea.
    Last edited by Brad0407; 12-15-2007 at 12:23 AM. Reason: changes to code
    Don't quote me on that... ...seriously

  4. #4
    Registered User
    Join Date
    Jun 2005
    The compiler generated assignment operator for a class invokes the assignment operators of any base classes, and then does a member-wise copy of any non-static data members specific to the class. The return value is a reference to the object that is being assigned (effectively a reference to *this). This allows chaining of assignments (eg a = b = c = d;).

    The behaviour described is modified in some circumstances (eg by attributes of or existence of assignment operators for base classes or data members). For example, if a base class has a private assignment operator, it cannot be called (implicitly or explicitly) in the content of a derived class.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using swap to make assignment operator exception safe
    By George2 in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2008, 06:32 AM
  2. Operator for array assignment.
    By 39ster in forum C++ Programming
    Replies: 9
    Last Post: 01-06-2008, 11:22 PM
  3. Assignment operator in a constructor argument
    By chadwickstein in forum C++ Programming
    Replies: 4
    Last Post: 09-30-2006, 04:08 PM
  4. constructors
    By shrivk in forum C++ Programming
    Replies: 7
    Last Post: 06-24-2005, 09:35 PM
  5. int vs BIG INT
    By rumi_red in forum C++ Programming
    Replies: 1
    Last Post: 10-30-2001, 04:15 AM