C++ for Embedded · Interview question

Can you overload a function on return type alone? Why or why not?

A strong answer

No. Overload resolution works from the arguments at the call site, and an expression like f() (or x = f()) doesn't always pin down which return type is wanted, the same call could appear in contexts expecting different types or no specific type. So the language requires overloads to differ in their parameter lists; int f() and bool f() declared together is a compile error. If you need different return types for the same logical operation, you either give the functions different names, take a parameter that distinguishes them, or use a template. (Note: a const and non-const member function can coexist, but that's overloading on the implicit this parameter's const-ness, which is a parameter difference, not a return-type difference.)

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Function & Operator Overloading

One name, several type-specific implementations the compiler picks for you, and giving your own types natural operators, without the runtime cost of C's void* or tagged dispatch.

More Function & Operator Overloading questions

Browse all 472 interview questions
Can you overload a function on return type alone? Why or why not? | EmbeddedPrep.io