CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2006
    Posts
    69

    Overloading operator

    Is it better to return a reference or a new instance of the object?

    For example :

    Code:
    
    class A 
    {
    
    private : 
    int seed;
    
    A(int s):seed(s){};
    
    A& operator + (const A &a); 
    {
    seed+=a.seed;
    return *this;
    }
    
    A operator + (const A &a);
    {
    return A(seed+a.seed);
    }
    Which one is better ?

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    Re: Overloading operator

    You should use the second one for this case. This is because operator+ should not have any side effect on it's operands.
    quoted from C++ Coding Standards:

    KISS (Keep It Simple Software):
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.

    Avoid magic number:
    Programming isn't magic, so don't incant it.

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading operator

    One of my first few discussions here was about overloading arithmetic operators

    The answer I eventually settled on was:
    Declare operator+= as a member function taking an object passed by const reference, returning by reference.
    Declare operator+ as a global function taking two objects passed by const reference, returning by value.
    Implement operator+ in terms of operator+=

    Code:
    A& A::operator+=(const A& rhs) {
    	seed += rhs.seed;
    	return *this;
    }
    
    A operator+(const A& lhs, const A& rhs) {
    	return A(lhs) += rhs;
    }
    The idea is to keep to the same semantics as the native operator+ and operator+=
    Last edited by laserlight; February 26th, 2006 at 08:51 PM.

  4. #4
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

  5. #5
    Join Date
    Oct 2005
    Location
    Bangalore
    Posts
    1,051

    Re: Overloading operator

    - Sreehari
    "Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
    " Everybody is sent to Earth on a purpose. I am so Lagging behind that i won't die." – Calvin

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured