Restrictions on Function Overloading
Function overloading is a very important feature of C++. It
makes our tasks easier, implements polymorphism and makes the program execution
faster. But there are obviously some restrictions on Overloaded Functions.
Let us see them in details.
Restrictions on Overloading
Functions
1.
First : Any two functions in a set of overloaded functions must have different argument list, i.e. all overloaded functions must have different signatures.
void func (int a, int b)
{
//body;
}
void func (int x, int y)
{
//body;
}
These two functions are not overloaded as their
signature is same. This will cause compiler error as both the functions are essentially
exactly same.
2.
Second : Overloading functions with argument lists of the same types(i.e. same signature), based on return type alone, is an error.
void func (int a)
{
//body;
}
int func (int b)
{
//body;
}
These two functions yield error. Different
return types with same function signatures are not considered overloaded.
Read more >> Function Overloading inC++
3.
Third : Member functions of a class cannot be overloaded solely on the basis of one being static and the other being non-static.
4.
Fourth : The typedef declarations do not define new types; they introduce synonyms for existing types. They do not affect the overloading mechanism.
typedef char * CH
void Print (char * a);
{
//body;
}
void Print (CH b);
{
// body;
}
The two functions here, have the same signature
as CH is nothing but a synonym for char *. Therefore, such declarations cause
compile time error.
Read more>> typedef in C++ (link will be restored shortly)
5.
Fifth : Enumerated types are distinct types and can be used to overload functions without any error.
Look at the following program
Output Screen:
Integer
Enum
Read more>> Enumeration in C++
6.
Sixth : The types “array of” and “pointer to” are considered identical for the purpose of distinguishing between overloaded functions. This is due to the fact that all arrays are always passed to functions as a pointer.
void func(int * a)
{
//body;
}
void func (int a[])
{
//body;
}
These two functions are same. An array
argument is always treated as a pointer.
See the following program.
Output Screen :
[error]Note: void func(int *) previously
defined here.
However, for multi-dimensional arrays these
restrictions do not count. These are not used much but just for information,
look at the following code:
Output Screen:
Array
Pointer
If you find something wrong or if you
wish to add some information in this article, feel free to comment on this post
or contact us at coding.nkcoder@gmail.com.
Which topics you want an article on? Comment down on this
post.
Do not stop here. Read all articles related to C++ here.
If you want to contribute any article for the website, feel
free to share it on coding.nkcoder@gmail.com. We will
publish it on the website with your name.
Post a Comment