Function overloading in C++

来源:互联网 发布:软件qa面试题 编辑:程序博客网 时间:2024/06/11 01:41

Function overloading, which seems to be a simple topic, is in fact much more complicated than we expect. An excellent book <C++ Primer> (I read the third edition) provides a full cover on it.

In short, there are two cases of function overloading, the normal function overloading in a certain scope and the member function overloading in a class scope. The compiler will follow three steps to select a correct form of a particular function call.

First of all, the compiler consider all the functions with the same name of that function call and visible at the calling point as the candidate functions. Meantime, figure out the number and the types of the real parameters of that call. In this step, the meanings of visible are different between overloading in a certain scope and in a class scope. Secondly, compare the number and the types with every candidate function's parameter list, to get the viable functions for that call. Any candidate function whose parameter list matches the real parameter list, which means that the real parameters have the same type with the corresponding ones in the parameter list of one function in three cases: accurate match, standard convertion, and user-defined convertion, can be a viable function of that real call. Finally, the best match among the viable functions is selected to finish that call. The rule for best match is that accurate match is better than standard convertion, and standard convertion is better than user-defined convertion.

To get more details about function overloading, I strongly recommend you to turn to <C++ Primer>. The related chapters in the third edition are: chapter 9 (the whole chapter focusing on the normal function overloading), chapter 15 (the whole chapter focusing on the member function overloading and the operator overloading of class), and chapter 19 part 3 (focusing on the overloading problem in the hierarchy of inheritance).

 
原创粉丝点击