0

Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. For example, following program fails in compilation.

#include<iostream> 
class Test { 
   static void fun(int i) {} 
   void fun(int i) {}    
}; 
  
int main() 
{ 
   Test t; 
   getchar(); 
   return 0; 
} 

I don't understand why the following example can run:

#include<iostream> 
class Test {
public:
    static void fun(double i) {
        std::cout << i << "\n";
    }

    void fun(int i) {
        std::cout << i;
    }
};

int main()
{
    Test t;
    t.fun(5.5);
    t.fun(4);
    return 0;
}
An Lê
  • 3
  • 1
  • In your first case, how would the program know whether to call the static one or the non-static one? There is no way for it to know so it refuses to compile - actually, that's a lot better than just choosing one randomly and then compiling. – Jerry Jeremiah Mar 02 '21 at 03:34
  • Does this answer your question? [C++ Overload Static Function with Non-Static Function](https://stackoverflow.com/questions/5365689/c-overload-static-function-with-non-static-function) – dxiv Mar 02 '21 at 03:38

2 Answers2

0

The second Example will run because the parameter types are different in both the function, i.e. double in the first and int in second. So function overloading takes place

Dhruv Kothari
  • 103
  • 2
  • 7
0

Function overloading only works when you have different set of parameters, in the example's case it's int and double. change the parameter data type.

mahibonu10
  • 11
  • 4