Possible Duplicate:
Overloading by return type
Why can't I declare three member functions like this:
void x(int a);
void x(String a);
int x(String a);
?
Possible Duplicate:
Overloading by return type
Why can't I declare three member functions like this:
void x(int a);
void x(String a);
int x(String a);
?
Because you can't overload by return type.
void x(string a)
and
int x(string a)
have the same signature. The signature is made of:
Which, in your case, are the same.
C++ does not allow you to overload functions based on the return type. Function overloading is only allowed based on the type of the arguments. This means that void x(String a)
and int x(String a)
are seen as the same function as far as overloading rules are concerned.
One important case that may be confusing (but is often used) is when const
is put at the end of a member function. That would look something like int number_of_peanuts(bool tasty_only) const
. That const
at the end means that the class that this member function is part of cannot be modified by this function.
However, this is actually just a special case of argument type overloading. When you have a member function that is not declared static
, there is implicitly an extra parameter added to your function, this this
pointer. This means that the example function I gave is roughly equivalent to int number_of_peanuts(Class const * this, bool tasty_only)
. If you didn't have const
at the end of the function, then instead it would be like int number_of_peanuts(Class * this, bool tasty_only)
.
So to summarize, the type and number of arguments are the only thing that allow you to overload. If you pass by value, as in void x(int a)
, then const
won't give you overload opportunities, because the outside world cannot tell the difference between whether you modify your copy or not. If you pass by reference or pass a pointer, then you can use const
with the thing they are referring to as overload options, so void x(std::string & a)
and void x(std::string const & a)
are different, because the world can tell if you modify a or not. Putting const
at the end of the function is another source of overload opportunity. And finally, and most obviously, void x(int a)
and void x(int a, int b)
is a legal overload because you have a different number of arguments.