Like Tree1Likes
  • 1 Post By laserlight

Operator = override

This is a discussion on Operator = override within the C++ Programming forums, part of the General Programming Boards category; I am trying to duplicate the string library (to learn it better... and I won't lie, it's for an assignment). ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Location
    Siloam Springs, Arkansas, United States
    Posts
    12

    Question Operator = override

    I am trying to duplicate the string library (to learn it better... and I won't lie, it's for an assignment).

    But I am having trouble trying to override the = operator.

    Here is what I have:

    Code:
    mystring& mystring::operator=(const mystring& str){
        
        char *copiedStr;
        
        if (*this == str) return *this;
        
        if (this->size() != str.size())
        {
            delete this;
            copiedStr = new char[str.size()];
            strcpy (copiedStr, str.c_str());
            this = copiedStr;
        }
        
        return *this;
    }
    I will admit that I do realize that this code is all jacked up. I have been playing with it so much that I don't even know where I originally started, so it's prolly best to just restart. But I'm stubborn.

    Here's the idea... (at least, how I think it should work)
    We'll call passing string as str1 and the destination (in this case "this") as str2.

    If str1 is the same as str2, do nothing
    Otherwise copy str1 to str2.

    I am assuming that you would have to make sure they are the same size, and I am under the impression that if they are not the same size, the easiest thing to do would be create a new array. Once the array is created, just copy str1 to str2 and return str2.

    However, I should be returning *this and I don't know how to change "this" to point to the new array.

    The error I am getting now is
    Code:
    error: lvalue required as left operand of assignment
    (referring to "this = copiedStr;")

    Can someone please point me in the right direction or show me where I can look to see how the string class is coded? I imagine it's got to be posted somewhere, but I can't find it.

  2. #2
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    >>I am assuming that you would have to make sure they are the same size...
    If you think about it, the only point where you have to make a new array is if str1 is bigger than str2. Otherwise there is room.

    >>copiedStr = new char[str.size()];
    Must be
    copiedStr = new char[str.size() + 1];
    because each C-style string must end with a '\0' which is not counted towards the length.

    Now, as for this
    this = copiedStr;
    What you need to do is get rid of the old string you have (which should some member that's a pointer), and substitute it with the new.

    So,
    delete [] m_str;
    m_str = CopiedStr;

    And then you return *this, a reference to the object itself, and not the actual string (that's an implementation details that the user should not know about!).
    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.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,445
    There are a few ways to do this. One way is to use the copy and swap idiom:
    Code:
    mystring& mystring::operator=(const mystring& str) {
        mystring temp(str);
        swap(temp);
        return *this;
    }
    Now all you have to do is make sure your copy constructor and destructor is correct, and write a swap member function.
    iMalc likes 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

  4. #4
    Registered User
    Join Date
    Oct 2011
    Location
    Siloam Springs, Arkansas, United States
    Posts
    12
    Quote Originally Posted by Elysia View Post

    delete [] m_str;
    m_str = CopiedStr;
    Thank you for this. The only question I have is, what is the "m_str"? Is that the current string?

    laserlight... thanks for your advice, but if I did that, wouldn't I still have to make a similar code that I am trying to do now with a swap member function? Or is that easier? Sorry, I'm kind of a noob.

    Thank you so much to both of you for your help.

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Quote Originally Posted by Amoxaphobic View Post
    Thank you for this. The only question I have is, what is the "m_str"? Is that the current string?
    It is whatever member variable that holds the string in your class. So I guess you could refer to it as "the current string," yes.

    laserlight... thanks for your advice, but if I did that, wouldn't I still have to make a similar code that I am trying to do now with a swap member function? Or is that easier? Sorry, I'm kind of a noob.
    No, swap simply swaps two variables. Take the contents of A and put it into B, and the take contents of B and put it into A. A swap function would be very trivial, as you see.
    But you will have to make sure your destructor and copy constructor works properly. But then, they should always be working.
    When creating a new class, you should implement a proper constructor, copy constructor and destructor. Then you can simply write the assignment operator (if it makes sense) by using this swap idom, and it works.
    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.

  6. #6
    Registered User
    Join Date
    Oct 2011
    Location
    Siloam Springs, Arkansas, United States
    Posts
    12
    Okay, so if that's the case, how do I access it (the m_str)? The function only passes the second string (the string in the which the "current" string will be). So, I guess that's where I am having all the issues. I have a feeling that's it's simple, but I just don't know what it is.
    Last edited by Amoxaphobic; 10-21-2011 at 10:51 AM. Reason: clarification

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Access what? Just so you know, the current instance your code is executing in can be acquired by *this.
    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.

  8. #8
    Registered User
    Join Date
    Oct 2011
    Location
    Siloam Springs, Arkansas, United States
    Posts
    12
    So... I guess I'm a bit confused. Isn't that what I had?

    Something to the extent of:
    delete [] this;
    *this = copiedStr;


    If I do that, I get an error? Sorry...

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Back to basics...

    If I have

    mystring str;
    str = "Hello World";

    Then the compiler has no idea how to assign a const char[] to a mystring. Therefore, we have to tell the compiler how to do it.
    We do this by creating an assignment operator, operator = (const char*). Note that the assignment operator is implemented inside mystring.
    So what happens when we execute that code?

    The compiler calls str.operator = (const char*).
    Inside this function, *this refers to str. That is, *this is of type mystring. But we can't just say *this = CopiedStr, because that is exactly what we are trying to define here.
    You know how you built this string, so you know what must be done to assign a new string into it.

    At the end, we return *this to enable chaining, such as
    mystr = a = b = c = d, ... ;

    *this will simply return the object itself, so it is not something you should be concerned with. You just need to make sure to successfully complete the copy operation, and then we end it with that return statement.
    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.

  10. #10
    Registered User
    Join Date
    Oct 2011
    Location
    Siloam Springs, Arkansas, United States
    Posts
    12
    Right, back to the basics. Sorry for that.

    I got it... I have to refer to how it's made. In this particular case I have a ptr_buffer (this->ptr_buffer) which is where the pointer actually is. So I use that.

    Thank you so much for your help and I apologize for the noob questioning.
    I think your signature is correct, and I'd like to know as well.... how the hell do you know everything?

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Quote Originally Posted by Amoxaphobic View Post
    I got it... I have to refer to how it's made. In this particular case I have a ptr_buffer (this->ptr_buffer) which is where the pointer actually is. So I use that.
    Right. That's how you do it.

    Thank you so much for your help and I apologize for the noob questioning.
    No need to apologize. We learn by asking what we don't understand and experiment.

    I think your signature is correct, and I'd like to know as well.... how the hell do you know everything?
    OK, that's not to brag or anything, but after you use a language for a certain amount of years, you get good at it.
    If you keep at it, you'll come back here one day and laugh at such a silly question and answer them for other newbies
    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.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,295
    You cannot use delete this; or delete[] this; from inside an assignment operator. What you can do, but really really should not do, is to call the destructor on this, and then the constructor on this, directly from the assignment operator.
    Have a read of this GOTW article: GotW #23: Object Lifetimes - Part II

    By using the copy and swap idiom, your data type becomes nicely exception safe as a bonus.

    Also, do not compare the strings before deciding to do the assignment. That does not save any work. Firstly if they are unequal, which is more likely, then it obviously is just extra overhead. Secondly, if they are actually equal then the only way you know this is when the string compare has walked the entire length of both strings and compared them character for character all the way along. That is unfortunately the same amount of work as doing a copy except without the allocation and deallocation. The longer the string is, the smaller the portion of time is taken by the memory management itself.
    Last edited by iMalc; 10-21-2011 at 02:38 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C# Lists - can I override Add() ?
    By gah_ribaldi in forum C# Programming
    Replies: 2
    Last Post: 12-11-2009, 09:47 PM
  2. Destructor Override!
    By vb.bajpai in forum C++ Programming
    Replies: 1
    Last Post: 06-26-2007, 07:14 PM
  3. Method Override
    By vb.bajpai in forum C++ Programming
    Replies: 3
    Last Post: 06-21-2007, 04:07 PM
  4. How do I override constructor in inheritance?
    By Loduwijk in forum C++ Programming
    Replies: 13
    Last Post: 03-24-2006, 08:36 AM
  5. override << ?
    By loobian in forum C++ Programming
    Replies: 2
    Last Post: 10-30-2001, 02:15 PM

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