c++: overload assignment operator


Results 1 to 14 of 14

Thread: c++: overload assignment operator

  1. #1
    Join Date
    Jul 2001
    Location
    US
    Posts
    29

    Angry c++: overload assignment operator



    I've gotta use the assignment operator in an unusual way, and I can't find resources online that explain it well.

    Suppose you're implimenting a class with a simple linked list:

    class LinkedList
    private:
    struct ListItem {
    char data;
    *ListItem pointer;
    };
    *ListItem head;

    I need to add a public function that will allow this to work:

    void main() {
    LinkedList NewList();
    NewList = a; //adds 'a' to NewList.ListItem.data

    This is a simplification of the problem, and I hope it makes sense. I don't even know what the function definition should look like...
    LinkedList::LinkedList & operator=(char foo) //?????

    Any insight is greatly appreciated. I cranked this out fairly quickly, so I hope it is clear...
    Last edited by yolabingo; 11-19-2002 at 05:59 AM.
    I'm not your soulmate, Homer. I'm more of a well-wisher, in that I don't wish you any specific harm.

    -Moe

  2. #2
    Join Date
    Aug 2002
    Location
    Berlin, Germany
    Posts
    189
    something like
    Code:
    LinkedList& LinkedList::operator= (const char foo)
    {
      //dosomething
    
      return *this;
    }
    is the usual way of overloading (well, with foo also being a LinkedList & of course). a good tutorial page seems to be here

  3. #3
    Join Date
    Jul 2001
    Location
    US
    Posts
    29

    well, with foo also being a LinkedList & of course

    Actually, the reason I'm having difficulty is that foo is NOT a LinkedList object. It is just a plain old character. Every reference I've found warns me about the pitfalls of the shallow copy you get when you use = with linked list objects, and I understand all that.

    I need to know the syntax to have an object call the = operator with a char (or int or whatever) as the argument.
    I'm not your soulmate, Homer. I'm more of a well-wisher, in that I don't wish you any specific harm.

    -Moe

  4. #4
    Join Date
    Aug 2002
    Location
    Berlin, Germany
    Posts
    189
    hmm. i don't understand your problem. the following code compiles and runs fine here:
    Code:
    class test
    {
    	char a;
    public:
    	test& operator= (const char foo)
    	{
    		a=foo;
    		return *this;
    	}
    
    	void print() { cout << a << endl; }
    };
    
    int main()
    {
    	test t;
    	t='f';
    	t.print();
    	return 0;
    }

  5. #5
    Join Date
    Jul 2001
    Location
    US
    Posts
    29
    hmmm

    that does look about right. maybe I just need some sleep
    I'm not your soulmate, Homer. I'm more of a well-wisher, in that I don't wish you any specific harm.

    -Moe

  6. #6
    Join Date
    Aug 2002
    Location
    Berlin, Germany
    Posts
    189
    that helps from time to time

  7. #7
    Join Date
    Feb 2000
    Location
    Idaho
    Posts
    780
    IMHO, you should maybe re-think doing that. It's not the expected behavior for the assignment operator. Generally you'd do a += to add an item to the list rather than =. And if you think about it, how do you intend on adding anything after the first with the way you're doing it? The answer is, you can't without making life a whole lot harder than it has to be (or having to write a function that makes the = operator you just defined useless).

    Just something to keep in mind.
    Energon-Software

    Registered Linux User #195465
    counter.li.org

    My Q3W Post was Slashdotted:
    The Q3W Post (Original Post Gone)
    The Slashdot Article

  8. #8
    Join Date
    Aug 2001
    Posts
    114
    If this is just a school assignment, I wouldn't worry too much about whether or not it is the 'best' way to implement the insert method. You should just recognize that this is not a good implementation.

    Code:
    LinkedList LinkedList::operator=(char a)
    {
    // insert a into the list
    return *this;
    }

    Just like he said above. I think the confusion came in when he said that the argument to the method was a linked list (which meant that if you were normally overloading '=' you would be passing a linked list as the arg).

    By the way, all that shallow copy stuff has to do with overloading '=' in the normal manner (list_a = list_b).

    Energon, why would it make it more difficult to insert something else into the linked list if you overload '=' to do inserts? Is there some need to have '=' overloaded to do a normal insert?

    Does this not work?

    [code]
    linked_list<int> a;
    a = 1; // 1
    a = 2; // 1 -> 2
    Last edited by UprightMan; 11-20-2002 at 09:46 AM.
    UM

  9. #9
    Join Date
    Aug 2002
    Location
    Berlin, Germany
    Posts
    189
    Originally posted by UprightMan

    Does this not work?

    Code:
    linked_list<int> a;
    a = 1; // 1
    a = 2; // 1 -> 2
    depends on your implementation of the operator. when you take my example from above, that would not work, because the 1 would be overwritten by 2. but that was just an example. the real implementation should do some list-inserting stuff there.

    and btw: i fully agree with energon. '+=' would be the better choice. but yolabingo asked and i replied.

  10. #10
    Join Date
    Aug 2001
    Posts
    114
    Well, I just want to clarify that I would use += as well

    I just don't see why you can't do successive inserts if you use '=' as an insertion operator (as you mention, not what you did in your example).

    Maybe Energon was talking about your example. I thought he was generalizing.
    UM

  11. #11
    Join Date
    Feb 2000
    Location
    Idaho
    Posts
    780
    Yeah, I was referring to the example. It's always overriding the same variable...
    Energon-Software

    Registered Linux User #195465
    counter.li.org

    My Q3W Post was Slashdotted:
    The Q3W Post (Original Post Gone)
    The Slashdot Article

  12. #12
    Join Date
    Jul 2001
    Location
    US
    Posts
    29
    Actually, this is for school. I tried to change the details of the assignment in my example enough so I wouldn't feel like I'm cheating, but I ended up asking a question that doesn't help me.

    Part of the project involves storing an int as a linked list of single-digit ints. So I've got something like this:

    Code:
    class IntClass{
    public:
    
    IntClass();
    IntClass(int x);
    ...
    
    private:
    struct IntNode {
    int data;
    *IntNode pointer;
    };
    };
    I think I have correctly created a constructor that takes an int as an argument and feeds each digit into the linked list, so the function call
    IntClass foo(123456);
    creates a 6-item list: 1,2,3,4,5,6

    I need to overload the = operator so that I can use an int as an argument:
    foo = 98766;

    I hoped to do something like this:
    Code:
    IntClass:: operator=(int x) {
    IntClass temp(x);
    return temp;
    }
    But can't figure out the syntax of the function header or function definition. I think it should be something like:
    Code:
    friend IntClass operator=(int x);
    
    IntClass::IntClass operator=(int x) {....}
    I'd love to be able to work out any logic errors, but I can't get the freakin' thing to compile -- errors usually indicate my function header doesn't match a function definition. How can I get this to work?
    Last edited by yolabingo; 11-21-2002 at 03:32 AM.
    I'm not your soulmate, Homer. I'm more of a well-wisher, in that I don't wish you any specific harm.

    -Moe

  13. #13
    Join Date
    Aug 2002
    Location
    Berlin, Germany
    Posts
    189

    Arrow sorry

    just had some time. :)

    i wrote these three files
    digitlist.cpp
    digitlist.h
    test.cpp


    *edit*
    === outdated ===
    the trick is, i wrote a private function IntToList(int), which takes an integer and fills the local list with the digits. this function is called both from the constructor and from the =-operator.
    === /outdated ===


    when i looked into your problem-description, my first thought was a copy-constructor. but that didn't work for me - somewhere i had a logical mistake and couldn't figure it out, so i got back to the =-operator again. but i will search for a solution...brb... ;)

    *edit*
    i've found it: when assigning this way a=b, the copy constructor is never called but the default assignment operator - didn't know there is one, i always thought the default copyconstructor is used in that case. so i also learned something today ;) let's see if i can update the class...brb...

    *edit2*
    got it to work :D the links above point to the new files. the output is of course different now:
    Code:
    13:32:20 ~/lnoforum/digitlist [552] > ./test
    // DigitList z(9); 
    DigitList[0x22fed8]::DigitList(9)
      DigitList[0x22fed8]::IntToList(9) [digits: 9]
    // z.print(); 
    DigitList[0x22fed8]::print() [digits: 9]
    // DigitList l(10890); 
    DigitList[0x22fec8]::DigitList(10890)
      DigitList[0x22fec8]::IntToList(10890) [digits: 0<-9<-8<-0<-1]
    // l.print(); 
    DigitList[0x22fec8]::print() [digits: 1->0->8->9->0]
    // l=170; 
    DigitList[0x22feb8]::DigitList(170)
      DigitList[0x22feb8]::IntToList(170) [digits: 0<-7<-1]
    DigitList[0x22fec8]::operator=(0x22feb8)
      DigitList[0x22fec8]::RemoveAll() [digits: 1->0->8->9->0]
      Copying [digits: 1->7->0]
    DigitList[0x22feb8]::~DigitList()
      DigitList[0x22feb8]::RemoveAll() [digits: 1->7->0]
    // l.print(); 
    DigitList[0x22fec8]::print() [digits: 1->7->0]
    // l=z;
    DigitList[0x22fec8]::operator=(0x22fed8)
      DigitList[0x22fec8]::RemoveAll() [digits: 1->7->0]
      Copying [digits: 9]
    // l.print(); 
    DigitList[0x22fec8]::print() [digits: 9]
    // }
    DigitList[0x22fec8]::~DigitList()
      DigitList[0x22fec8]::RemoveAll() [digits: 9]
    DigitList[0x22fed8]::~DigitList()
      DigitList[0x22fed8]::RemoveAll() [digits: 9]
    13:32:21 ~/lnoforum/digitlist [553] >
    whatever you don't understand: just ask! ;)

    maybe i put the interesting code also here into the post:
    Code:
    DigitList& DigitList::operator= (const DigitList &l)
    {
      printf("DigitList[%#x]::operator=(%#x)\n",(int)this,(int)&l);
      if (this!=&l)
      {
        RemoveAll();
        printf("  Copying [digits: ");
        Digit *tmp = l.head;
        Digit *prev = 0;
        while (tmp)
        {
          Digit *dig = (Digit *)malloc(sizeof(Digit));
          dig->d=tmp->d;
          printf("%d",dig->d);
          // if head is 0, this is the first digit -> point head to it, 
         // else set the previous digits next pointer correctly
          if (!head) head=dig;
          else prev->next=dig;
          // one step further in l
          tmp=tmp->next;
          // the last digit needs 0 in next
          if (!tmp) dig->next=0;
          else printf("->");
          // remember the new digit, because its next-pointer needs to be set in the next loop
          prev=dig;
        }
        printf("]\n");
      }
      return *this;
    }
    when looking at the code l=170 with l being of type DigitList, the compiler knows, that there is a constructor for a DigitList-object, that takes an int-parameter. so it constructs an internal DigitList-object from the integer 170 (in the example above that temporary object is located at 0x22feb8) - afterwards the =-operator is called with that temporary object.

    notice, that the assignment-operator takes DigitList & as an argument.

    when you don't implement this version, the default =operator for two DigitLists is taken and this one does the evil shallow copy, so you have no reference to the old digits in the left List anymore an a classical memory leak.
    example:
    Code:
    DigitList a(71);
    DigitList b(12);
    a=b;
    if you don't overwrite the default =-operator (the one taking an DigitList&-argument), you are not able to free the space you allocated for the '7' and '1' in the constructor for a. you see?

    that's why it is necessary, that you implement
    operator=(DigitList&foo)
    Last edited by Rüpel; 11-21-2002 at 09:13 AM.

  14. #14
    Join Date
    Feb 2015
    Posts
    1

    Tools for writing essays

    Prompt service on writing essays

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •