Thread: Function doesn't return an object

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    2

    Arrow Function doesn't return an object

    Hi there.

    I've built a class that contains an array of characters and implements several methods to manage the array.

    I want to redefine operator + so an instruction like b = a + 'x' adds the character 'x' to the array contained in a and puts the result in the array contained in b.

    This is what I try:

    Code:
    // This function is supposed to manage this kind of instructions:
    //   b= a+ 'x' , where a and b are instances of SetOfChar.
    //   Of course, a is referred as 'this' inside the function.
    
    SetOfChar SetOfChar::operator+(char c){
    
          // 1) Create a new object with same data than this (a)
    	SetOfChar res(*this);    
    
          // 2) Add the character
    	res.addChar(c);
    
          // 3) RETURN THE RESULT AS AN OBJECT (doesn't work!)
    	return res;
    }
    I've also tried to return a reference to the local object instead of the object itself, but it won't work.

    Both the constructor and the addChar method work properly.

    How am I supposed to create an object inside a function and then return it as a result?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    If your copy constructor works then the problem lies with the assignment operator. In general if you have to write a copy constructor, assignment operator or destructor you need all three. Normally binary operators that return temporaries are built as free function syntatic sugar out of '+='

    Code:
    class foo {
        public:
        foo & operator += (char c) {... return *this;}
    };
    
    inline foo operator + (const foo &f, char c) { return foo(f)+=c; }

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    2

    Thumbs up

    I found out that my problem was that I hadn't declared operator = , so I couldn't make the expression b = a + 'x' work properly.

    After all, the function DID return the object correctly.

    Anyway, I also made the changes you suggested, as it's a much more elegant solution than the one I used before.

    Thank you very much for your answer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  3. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM