Tuesday, March 30, 2010

C++ function overloading on Return Type

It is possible to overload the functions based on return type.

I am not talking about the functions with 'CV' qualifier.
For e.g,
class C
{
public:
void foo() const;
int foo() volatile;
double foo() const volatile;
};

This way we can have overloading. But in reality they are not overloaded for same object. It depends on what kind of object. For eg, when you create const object of C, it will call void foo(), similarly for volatile , it is int foo() etc...
So in real sense they are not overloaded.

Where as if you use template, you can overload the functions based on the return type.

class OverLoad
{
public:
template < T > // just declaration , no definition
T GetMe();
};

template <>
int
OverLoad::GetMe()
{
return int;
}

template <>
std::string
OverLoad::GetMe()
{
return std::string();
}template <>

double
OverLoad::GetMe()
{
return 2.2;
}
etc...

These functions can be called by the same object.

No comments: