Overloading Assignment Operator, this pointer

This is a discussion on Overloading Assignment Operator, this pointer within the C++ Programming forums, part of the General Programming Boards category; Hi, i'm confused about these lines of code: (this is in the POV of me talking to the creator of ...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    70

    Overloading Assignment Operator, this pointer

    Hi, i'm confused about these lines of code:
    (this is in the POV of me talking to the creator of a book thats why im saying you guys(as in the writers of the book))
    Code:
    String& operator=(const String& rhs) //Assignemt operator
    {
        if(this == &rhs)
            return *this;
    
        int len = strlen(rhs.mData);
    
        delete[] mData;
    
        mData = new char[len+1];
    
        for(int i=0;i<len;++i)
        {
            mData[i] = rhs.mData[i];
        }
    
        mData[len] = '\0'
    
        return *this;
    }
    i dont get why you put, this == &rhs , does it mean if the address this is pointing to is the same as the address of rhs?

    and also when u guys used the bracket operator in the for loop is it like a replacement for dereferencing the pointer to them?

    and why did u guys return *this when the return value is a String&? what does String& mean, does it mean a reference to a String object? i dont get it why return *this, does *this mean that you dereferenced the object calling it and then you return the actual object?

    and can you explain on what the this pointer is? i dont really get what it is.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,441
    Quote Originally Posted by cuo741
    i dont get why you put, this == &rhs , does it mean if the address this is pointing to is the same as the address of rhs?
    It is a check for self-assignment, i.e., if you somehow attempt to assign an object to the same object, then the copy assignment operator does nothing except to return the object itself.

    Quote Originally Posted by cuo741
    and also when u guys used the bracket operator in the for loop is it like a replacement for dereferencing the pointer to them?
    Yes, in that rhs.mData[i] is equivalent to *(rhs.mData + i).

    Quote Originally Posted by cuo741
    and why did u guys return *this when the return value is a String&? what does String& mean, does it mean a reference to a String object? i dont get it why return *this, does *this mean that you dereferenced the object calling it and then you return the actual object?
    Yes, it means "reference to String". The idea is to return the current object by reference.

    Quote Originally Posted by cuo741
    and can you explain on what the this pointer is? i dont really get what it is.
    A pointer to the current object, i.e., the object for which this member function is being called.

    By the way, this particular implementation of the copy assignment operator is not exception safe. new char[len+1] might throw an exception, so you should only delete[] mData after that, i.e., you should use another pointer to hold the result of new char[len+1] until you are sure that no more exceptions can be thrown. If you had an exception safe swap function, then you could use it along with the copy constructor and destructor to implement the copy assignment operator:
    Code:
    String& operator=(const String& rhs)
    {
        String temp(rhs);
        swap(temp);
        return *this;
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,207
    Not only is this method (in the original post) unsafe in the face of exceptions, the test for self-assignment is not guaranteed to work either. Consider, for example, a class that provides a unary operator&(). Admittedly, a String class is unlikely to implement a unary operator&(), but it is a concern to be aware of.

    The trade-off of the "create a local copy and swap contents" technique described by laserlight is that it uses additional memory (at least, until the operator=() returns). In most application domains, unless memory is VERY constrained, that is a small price to pay for strong levels of exception safety.
    Right 98% of the time, and don't care about the other 3%.

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    70
    I haven't learned how to throw exceptions yet, the book covers that in later chapters so this would be the appropriate code for my level of programming but, later on i'll make sure to fix that.

    I have a question about the return type, so if you put String& as the return type and you return a object, will that make a reference to that object? So would the return type act as like, "here give me something and ill make a reference to the thing you gave me" ??
    Last edited by cuo741; 12-06-2010 at 08:44 PM.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,207
    Quote Originally Posted by cuo741 View Post
    I haven't learned how to throw exceptions yet, the book covers that in later chapters so this would be the appropriate code for my level of programming but, later on i'll make sure to fix that.
    The code you're using invokes operator new, which (by default) throws an exception if it fails. Which means it is preferable to use techniques that won't screw things up when an exception is thrown.

    I realise, for you, that is a "chicken and egg" dilemma for you at present. However, it is better to learn good habits even if you don't necessarily know right now why they are good habits.

    Quote Originally Posted by cuo741 View Post
    I have a question about the return type, so if you put String& as the return type and you return a object, will that make a reference to that object?
    Approximately, yes. There are some constraints - such as a need to ensure the object being returned (by reference) still exists after the function returns. Attempting to use a reference to a non-existent object tends to give unwanted consequences (such as crashing programs).

    Quote Originally Posted by cuo741 View Post
    So would the return type act as like, "here give me something and ill make a reference to the thing you gave me" ??
    That question is as clear as mud.
    Right 98% of the time, and don't care about the other 3%.

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    70
    What i meant was like, if i return an object will the return value come out as a reference to that object but you're arent actually returning the actual object?

    And also, in this other snippet of code:

    Code:
    String::~String()
    {
          delete[] mData;
          mData = 0;
    }
    heres the class definition:
    Code:
    class String
    {
      public:
        String();
        String(const char* rhs);
        String(const String& rhs);
        ~String();
    
        String& operator=(const String& rhs);
    
      private:
        char* mData;
    };
    i dont get why you delete mData, i know that mData points to the dynamically allocated char array but, if we delete mData, is mData alone just the address of char array and not the char array itself?
    Last edited by cuo741; 12-07-2010 at 01:33 AM.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,207
    A reference is a handle to an object (also described as an alias, or an alternative name). A handle is not the same thing as the object, but provides a means of accessing that object.

    If a function returns a reference, it returns a handle to an object.
    Right 98% of the time, and don't care about the other 3%.

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    70
    But, we don't return a alias to the object, we just return the object itself dont we though? I'm sorry for the trouble, thank you for the help

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,441
    Quote Originally Posted by cuo741
    But, we don't return a alias to the object, we just return the object itself dont we though?
    You are returning an alias to the object. The return statement only tells part of the story; the return type is important too.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    70
    I still kinda dont get it, i sort of get it but, i'm still confused on the return value and stuff. Can you explain why is that the return value is String& and we return an object(*this) and in the book it says return a reference to *this object.

  11. #11
    Registered User
    Join Date
    Jun 2005
    Posts
    6,207
    The function does not return an object. It returns a reference.

    In C++, the name of an something is also technically a reference to that something. That is equally true whether that something is an int, a string, a pointer, or an instance of a class.

    There are many other ways to refer to an object. The name is only one means of obtaining a reference to an object.

    Within nonstatic member functions of classes, "this" is a pointer containing the address in memory of the object being acted on. "*this" is a reference to the same object.

    So "return *this;" obtains a reference to the object pointed to by this. If the return type of the function is a reference, that is what is returned. If the return type is a value (eg if your function returns String rather than String &) the value (or contents) of the object is copied, so the caller receives a copy of the object *this.
    Right 98% of the time, and don't care about the other 3%.

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,449
    Quote Originally Posted by cuo741 View Post
    i dont get why you delete mData, i know that mData points to the dynamically allocated char array but, if we delete mData, is mData alone just the address of char array and not the char array itself?
    mData points to the address in memory where your allocated array is. The only thing that happens after you call delete is that the allocated array isn't there at that address anymore. But a pointer cannot know that. It simply contains a memory address.
    As an analogy, take a sign. It points to somewhere, say, a house. But we can later demolish this house and the sign will still point to where that house was.

    As for returning a reference to *this...
    You realize that this is a pointer, right? It points to the location in memory where the current object is. But a reference is an alias, not to a memory address, but to an object. When you create a local object, say String a, then a is the object and not a memory address pointing to the object. Thus, when we create a reference to a, say String& b = a, then b is an alias for the object a.
    Thus, we need to dereference this to get the actual object this points to. That is what we create an alias for.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Argument from incompatible pointer type
    By AmritxD in forum C Programming
    Replies: 3
    Last Post: 08-15-2010, 03:23 PM
  2. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  3. Pointer assignment
    By MAx12345 in forum C Programming
    Replies: 16
    Last Post: 07-10-2008, 10:42 PM
  4. warning: assignment from a incompatible pointer type
    By enderandrew in forum C Programming
    Replies: 8
    Last Post: 09-22-2007, 04:07 AM
  5. assignment makes pointer from integer
    By crescen7 in forum C Programming
    Replies: 4
    Last Post: 06-25-2002, 10:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21