Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 478
James C Avatar asked Feb 07 '14 00:02

James C


3 Answers

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.

like image 91
David Hammen Avatar answered Oct 20 '22 01:10

David Hammen


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

like image 34
user207421 Avatar answered Oct 20 '22 01:10

user207421


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.

like image 21
rcgldr Avatar answered Oct 20 '22 01:10

rcgldr