Function Overloading In C++.
Hazem Khaled
Embedded Linux Content Creator | Embedded Linux Engineer at Valeo | C/C++ | Embedded Linux | ISAQB - Foundation Level | YOCTO
Objectives:
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.
领英推荐
// 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 ?
// 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 ?
Senior Functional Safety @ eJad | ISO26262 | Embedded Systems
2 年???? ????? ????? ?? ???? ??