Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading by return type

I read few questions here on SO about this topic which seems yet confusing to me. I've just begun to learn C++ and I haven't studied templates yet or operator overloading and such.

Now is there a simple way to overload

class My { public:     int get(int);     char get(int); } 

without templates or strange behavior? or should I just

class My { public:     int get_int(int);     char get_char(int); } 

?

like image 656
Shoe Avatar asked Mar 05 '12 15:03

Shoe


People also ask

What is return type in method overloading?

Function overloading and return type in C++ The function overloading is basically the compile time polymorphism. It checks the function signature. If the signatures are not same, then they can be overloaded. The return type of a function does not create any effect on function overloading.

Why we Cannot overload a function on return type?

You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression. GetVal(); What does the compiler do now? The compiler could just emit an "Ambiguous return type" message and refuse to compile.


1 Answers

No there isn't. You can't overload methods based on return type.

Overload resolution takes into account the function signature. A function signature is made up of:

  • function name
  • cv-qualifiers
  • parameter types

And here's the quote:

1.3.11 signature

the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. [...]

Options:

1) change the method name:

class My { public:     int getInt(int);     char getChar(int); }; 

2) out parameter:

class My { public:     void get(int, int&);     void get(int, char&); } 

3) templates... overkill in this case.

like image 166
Luchian Grigore Avatar answered Sep 18 '22 08:09

Luchian Grigore