Does C++ replace built-in operators with function calls?

Viewed 174

I was recently reading about operator overloading in C++. So, I was wondering whether the built-in operators are replaced by function calls behind the scenes.

For example, Is a + b(a and b are int types) replaced by a.operator+(b)? Or the compiler does something different?

3 Answers

There is no int::operator+. Whether the compiler chooses to compile a + b directly to assembly (likely) or replace it with some internal function like int __add_ints(int, int) (unlikely) is an implementation detail.

The internals of the compiler are complex. On a conceptual level, the answer is YES. Whenever a compiler sees a + b, it does have to check for known functions with the name operator+ and replace it with a call to the right function.

In practice, their are 2 important nuances to make:

  • The compiler knows about fundamental types (which you can't override), it doesn't need to insert a function call it can immediately insert the right 'instructions'
  • Inlining is an important optimization, which will remove the function call when interesting

Maybe. Many arithmetic operations map dir calypso into CPU instructions, and the compiler will just generate the appropriate code in place. If that’s not possible, the compiler will generate a call to an appropriate function, and the runtime library will have a definition of that function. Back in the olden days floating-point math was usually done with function calls. These days, CPUs for desktop systems have floating-point hardware, and floating-point math is generated as direct CPU instructions. But embedded systems often don’t have hardware for that, so the compiler generates function calls instead.

Back in the really early days, even integer math was sometimes done with function calls. Because of his, the IBM 1620 was sometimes referred to as the CADET: Can’t Add, Doesn’t Even Try.

Related