How does C++ know which function to call to compute a given expression?

Viewed 73

Typically, a standard function is called by functionName(list of arguments). Another standard way to call a function of an object is object.functionName(list of arguments). Both methods are clear and easy to understand since the function signatures are called in the exact order.

However, when it comes to the below:

  • A unary operator overloading: classA::operator-(), for example, doesn't take any argument. So when we write object2 = -object1,assuming object2 and object1 are both instances of classA, how does C++ know that it has to call classA::operator-() since we didn't write object2 = object1.operator-()?
  • A global function that defines the + operation between 2 objects for example Complex operator+(int number, const Complex& c). So when we write answer = 10 + aComplexNumber, how does C++ know which function to call since we didn't write operator+(10, aComplexNumber)?
  • A classA::operator[] operator overloading: so when we call object[argument]. How does C++ know which function to call since we didn't write object.operator[](argument)?

Edit: thank you all for the suggestions. I have edited my question to make it clearer.

1 Answers

This all depends on the operator.

Class::operator- () only operates on one item, so therefore, it does not need an argument since it can just be a member overloaded operator. (i.e. this will be operated on). This unary operator's return type should be the same as the object:

Class obj1;
obj1 = -obj1; //Calls the unary operator- and then the operator=

Now, let's suppose you want to implement the operator again but have it do operations on 2 Objects. That's where we add two different arguments and make it a non-member overloaded operator. For example: operator-(const Class & lhs, const Class & rhs), this will also most likely return an Class and will be called when you create two Class and subtract one from the other:

Class obj1;
Class obj2;
Class obj3 = obj1 - obj2; //Calls the non-member operator then operator=

Some overloaded operators must be member overloaded operators, such as the assignment operator= (const Object & rhs) and by default, the left-hand-side is this since you are assigning this Object to the rhs.

So again, it depends on the operator. You'll have to be more specific if you want more details on a specific operator.

Related