0

Consider this code, where I define a class called Thing:

 1 class Thing{
 2     public:
 3         int things;
 4         int stuff;
 5 };
 6
 7 int main(){
 8     Thing foo, bar;
 9     foo + bar;
10     return 0;
11 }

This question concerns line 9. Trying to apply the + operator between objects which aren't int or float etc. raises an error, as expected:

no match for 'operator+' in 'foo + bar'

So here's my question. What do I need to do to the definition of Thing in order to make the operation Thing + Thing = valid output?

For example, foo + bar = foo.things + foo.stuff + bar.things + bar.stuff.

Johan
  • 343
  • 1
  • 4
  • 13
  • 2
    Google "Operator overloading" – robbannn Feb 03 '15 at 13:04
  • What are you trying to do? You haven't told us. Your examples imply that you mean for `foo + bar` to exist on the LHS of an assignment; do you intend to perform an assignment to a temporary (why?) or to tie `foo` and `bar` together (wrong operator bub)? Can you provide a _concrete_ example of your desired usage? – Lightness Races in Orbit Feb 03 '15 at 13:07
  • The intention is to make `foo + bar` into a valid operation, which doesn't raise an error. The intention is ambiguous. The operation could return an `int`, a new `Thing`, or any other type. – Johan Feb 03 '15 at 13:10

0 Answers0