How does function overloading work at run-time, an

2019-05-05 12:15发布

Let's say I have a class named ClothingStore. That class has 3 member functions, that point a visitor to the right department of the store. Member functions are ChildrenDept, MenDept and WomenDept, depending on whether the visitor is a child, a man or a woman.

Function overloading can be used to make 3 functions that have same name, say, PointToDept, but take different input argument ( child, man, woman ).

What is actually happening on run-time when program is executing ?

My guess is that compiler adds switch statements to the program, to select the right member function. But that makes me wonder - is there any benefit in terms of program performance when using overloaded functions, instead of making your own function with switch statements? Again, my only conclusion on that part is code readability. Thank you.

3条回答
\"骚年 ilove
2楼-- · 2019-05-05 12:26

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.

查看更多
闹够了就滚
3楼-- · 2019-05-05 12:38

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'.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-05 12:50

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.

查看更多
登录 后发表回答