-1
class A{
..........
..........
};

int x;
A a;

x=a + x;  // option 1
x=x + a;  // option 2
x+=a; // option 3

Will the operator + overload for all option 1 2, & 3 will be same? i.e. int A::operator+(int s)

if not why and what for others?

Kumar Roshan Mehta
  • 3,078
  • 2
  • 27
  • 50

3 Answers3

2

No.

This will call A::operator +(int), or operator +(A, int):

x=a + x;  // option 1

This will call operator +(int, A) (there's no such thing as int::operator +(A)):

x=x + a;  // option 2

This will call operator +=(int, A) (but you had better make the first argument A&, not just A or you won't actually be able to write a working += operator). There's no such thing as int::operator +=(A):

x+=a; // option 3

The reason they call different operator overloads is because they are different... not sure what else to tell you.

user253751
  • 57,427
  • 7
  • 48
  • 90
1

No operator overloading needed at all, since you basically do int + int or int += int.

However, for completeness, for an operation such as A + B the overload resolution is

  1. A.operator+(B)
  2. operator+(A, B)

For += it's different since it's a separate operator, operator+=. It can't have any non-member overload (no assignment operator can), so for A += B the only possible attempt is A.operator+=(B).


After your edit, option 1 is still A.operator(x) or operator+(A, x) (as outlined above).

Option 2 can't have a member overload, so the only viable variant is opetrator+(x, A), or x + static_cast<int>(A).

Option 3 can only be x += static_cast<int>(A).

The static_cast<int>(A) option will use an operator int overload. If that doesn't exist then those alternatives are not possible and you will get an error when building.


I also recommend e.g. this operator overloading reference. And of course that you read a few good books.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

In your example,if you do like A::operator+(int s),then this overloading does not work for x+a,unless you define a type conversion like operator int(). Because the operator + as member function will has the implicit this pointer as the rhs parameter.

So it's recommended for you to overload the operator + as non-member function.And if necessary,provide a implicit type conversion likeoperator int(),or A(int);

Once you decide to overload operator+,it's recommend to provide operator+= as well,so as *,/,- . Because the compiler will not generate the operator+= automaticlly for you.

choxsword
  • 3,187
  • 18
  • 44