Search code examples
c++header-filesoverloading

C++: overloading with 2 functions, one in the header file, one is not


Suppose I declared (in c++, VS 2010), in one of the header file a function named "void f(int x)", then implemented it on the respective cpp file. While trying to add an overloading function (void f(int x, int y) ) in that source file only (No declaration in the header), I am getting an error "function does not take 2 arguments".
(This function is written above the calling function).

The header file doesn't have any implemented code.

Did I violate some c++ rules, or it is only because of using the Visual? Must I declare all overloading functions in the header file (or none at all)?

Edit: Source File:

int findNodeRec(int data, NodeTree *root) 
{ 
    return 1;
}
int Tree::findNodeRec(int data) 
{ 
    return findNodeRec(data, m_root); 
} 

Solution

  • The problem is that the one parameter version is defined as a class member while the two parameter version is a free function. When the compiler is trying to find candidates to call, it won't mix different scopes so it only sees the class scope version, then tries to pick the best overload based on parameters.

    Just call ::f(x, y) instead and it will look in the global scope for the free function. Note that it wouldn't matter if the free function were declared in the header or not. The compiler still couldn't find it.