Search code examples
c++overload-resolution

function overloading and reading fdump-tree-all output


I was looking into a function overloading problem listed below and found that the following code doesn't compile.

#include<iostream>
class Test {
   static void fun(int i) {}
   void fun(int i) {}   
};

int main()
{
   Test t;
   return 0;
}

My understanding was that member functions when compiled implicitly have an extra parameter, a pointer to the object in the compiled function. I am not sure what happens to the static functions. Now to figure out what the compiler was doing I tried running g++ -fdump-tree-all failed_overload.cxx and I got the files listed below:

         failed_overload.cxx.001t.tu
         failed_overload.cxx.002t.class
         failed_overload.cxx.003t.original
         failed_overload.cxx.004t.gimple
         failed_overload.cxx.204t.statistics

I looked into gimple output and found the following:

**

static void Test::fun(int) (int i)
{
  GIMPLE_NOP
}
void Test::fun(int) (struct Test * const this, int i)
{
  GIMPLE_NOP
}

**

It seems like the static function just has the int parameter but the member function has the extra this parameter. If that is the case why is the compilation failing and why cant we overload the static function with the same signature.


Solution

  • If you had both static and non-static functions taking the same set of parameters, then in a call from a method of the class (non-static) it would be impossible to distinguish whether the programmer wants to call static or non-static function. Example:

    #include<iostream>
    class Test {
       static void fun(int i) { std::cout << 2*i; }
       void fun(int i) { std::cout << i; }   
       void otherFunc() {
          fun(3); // Ambiguity: is static or non-static function intended?
       }
    };
    
    int main()
    {
       Test t;
       t.otherFunc();
       return 0;
    }