How does function overloading work at run-time, and why overload?

家住魔仙堡 提交于 2019-12-05 12:10:17

From Gene's comment:

The compiler sees three different functions just as though they had been differently named.

In the case of most compilers, they are differently named. This used to be called name mangling where the function name is prefixed by return type and suffixed by the parameter types.

My guess is that compiler adds switch statements to the program, to select the right member function.

That's a bad guess. C++ is a statically typed language. The type of a variable does not change at runtime. This means the decision as to which non-polymorphic overload to call is one that can always be made at compile time. Section 13.3 in the standard, Overload resolution, ensures that this is the case. There's no reason to have a runtime decision when that decision can be made at compile time. The runtime cost of having a non-polymorphic overloaded function in most implementations is zero. The only exception might be a C++ interpreter.

How does function overloading work at run-time

It doesn't. It works at compile-time. A call to an overloaded function is no different at runtime from a call to a non-overloaded function.

and why overload? ... is there any benefit in terms of program performance when using overloaded functions, instead of making your own function with switch statements?

Yes. There is no runtime overhead at all, compared with 'making your own function with switch statements'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!