Search code examples
c++overloadingreturn-typeoverload-resolutionfunction-declaration

Is this overloading?


If I have two functions like this:

int f ( int a )
{}

void f ( signed a )
{}

are they overloaded?

When in main() I call f(5), I get an error:

old declaration ‘void f(int)’

Solution

  • Type specifiers signed and int (used alone without other type specifiers) define the same signed integer type.

    That is you may equivalently write for example

    int a;
    signed a;
    signed int a;
    int signed a;
    

    So the functions in the question have the same parameter declaration.

    However they have different return types

    int f ( int a )
    { }
    
    void f ( signed a)
    {}
    

    That is the same function is redefined with different return types. The return type does not take part in function overloading.

    So the compiler issues an error that the same function is defined twice with different return types.

    From the C++ 14 Standard (13.1 Overloadable declarations)

    2 Certain function declarations cannot be overloaded:

    (2.1) — Function declarations that differ only in the return type cannot be overloaded

    If you would change the parameter declaration in one of the functions for example the following way

    int f ( int a )
    { }
    
    void f ( unsigned a)
    {}
    

    then the functions would be overloaded and this statement

    f( 5 );
    

    would call the first overloaded function because the integer literal 5 has the type int..