jayjay
jayjay

Reputation: 1047

C++ Class addition method

I have a C++ class that primarily contains an integer and I wish to ceate a method that adds two of them together, I dont want to overload the + operator.

I belive I have 2 options:

var_result = var1.add(var2);

var_result.add(var1, var2);

where var_result, var1 and var2 are of the same type.

I think the 1st one is more intuitive ot use, but the seccond one is not creating an instance which might give performance benefits. How should I go about making this decision? This is going to be directly visible to others using my code.

I realize I might be dicing with the "opinion based" closure of this question but hopefully there is some degree of objectivity here.

Upvotes: 1

Views: 168

Answers (2)

quantdev
quantdev

Reputation: 23793

Write you add() method with the same (preferred) semantics used for operator+ : write a free method that returns a new object by value.

Example :

var_result = add(var1, var2);

var_result2 = add(var1, var2).add(var3, var4);

// etc...

It allows you to chain methods, and respect the usual semantics available for primitive types.

Note:

  • Usually, the free function operator+ would make use of the class member operator+= that you would define for your type, allowing also var_result += var1

So your final design should look like :

class X
{
  public:
    X& operator+=(const X& rhs) { ...; return *this; }
};

X add(X lhs, const X& rhs)
{
    return lhs += rhs;
}

Or if you don't want operator+= either (which would makes sense, at least for consistency) :

class X
{
  public:
    X& add(const X& rhs) { ...; return *this; }
};

X add(X lhs, const X& rhs)
{
    return lhs.add(rhs);
}

Upvotes: 3

Jack
Jack

Reputation: 2273

Go with creating a new item, because any space/time performance costs would be tiny and there are serious advantages to using immutable objects.

Upvotes: 1

Related Questions