Function Overloading In C++.

Function Overloading In C++.


Objectives:

  • Understanding What is meant by overloading in C++.
  • How does C++ deals with overloading under the hood.
  • Problem arises when using overloading.
  • Understand NULL and nullptr and their relation with overloading.

Understanding What is meant by overloading in C++.

Overloading in C++ happened when two or more function has the same name but different signature.

Signature of a function = function name + arguments types + # of arguments.

// Example: let's assume that we have the following two prototypes.


void print(int _x); // signature of this function print_int__x
void print(string _s); // signature of this function print_const_char__s.                                          
How does C++ deals with overloaded functions ?
// back to our example above if you take attention to the comments, we can see that c++ interpret the function with the following schema, 
[function name]_[data type of first argument]_.... and so on.        

  • If we look carefully in the assembly output for those two functions we would like see something like that:

// for void print(int _x) .
_[print][i], @function //print is function name, i (Integer datatype).
// for void print(string _s).
_[print]_[string] // print is function name, string data type for _s argument.        
Problem arises when using overloading.
// imagine that we have the following two functions definitions.


void print(int _x, int _y)
{
  cout << "integer = " << _x + _y << endl;
}


void print(float _f1, float _f2)
{
  cout << "float = " << _f1 + _f2 << endl;
}


int main ()
{
   int x = 10;
   float y = 20.f;
   // now call print function.
  print(x, y); // what would you expect in this case ? try it ! Do you think c++ will support you on this ?        
NULL and nullptr

One of the common questions is that why c++ introduces nullptr ?

  • To solve the ambiguities that happened in the last example.

// null pointer: pointer point to nothing.
#define NULL (0) 




// let's assume the following example.
bool isNull(int _x);// version #1
bool isNull(int* _x);// version #2.


// regardless the definitions for those functions let's use them directly.


int main ()
{
  int * _p  = NULL;
  
 // lets make a call to isNull.
 isNull(_p);//what would you expect in this case ? c++ will calll #1 or #2 ?          

  • The above code will run version #1 because NULL is defined as (0), in c++ 11 there is a new data type called nullptr that can be used in such a case instead of NULL.

https://stackoverflow.com/questions/20509734/null-vs-nullptr-why-was-it-replaced

Ahmed Elameer

Senior Functional Safety @ eJad | ISO26262 | Embedded Systems

2 年

???? ????? ????? ?? ???? ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了