Chinese Yellow Pages | Classifieds | Knowledge | Tax | IME

C++ function overloading, name mangling, name hiding are somehow related to the same issue: overload resolution at compile time ( note override is run-time resolution).

What is C++ Function overloading:

two or more functions have same name and but have different parameters/signature.

The way compiler distinguishes those different functions is adding additional information about arguments to function names called Name Mangling. The extern “C” in C++ is to make sure the function names are unmangled, thus being able to be called in C style.

Overloading with inheritance

The function overloading become interesting in the case of c++ inheritance

 

class Base { public:  virtual void f() {}; }

class Derived: public Base { public: void f(int){}; }

int main(){ Derived c; c.f(); return 0 }

 

if we call Derived.f(), the compiler will fail. why?

In C++, phases of the function call process are as following

  • Name lookup
  • Overload resolution
  • Access control

Once a name f(int) was found in the name lookup phrase in the Derived class, the compiler will move to the overload resolution phrase: now the C++ name hiding rule will hide all the same name functions ( even it is a virtual function) in Base class, which means Derived.f() is invisible, though Derived.Base::f() is still visible. So there is no f() in this scope, the compile will fail.

why do we need C++ name hiding rule?

One reason is due to fragile base class problem described in http://thesyntacticsugar.blogspot.com/2011/10/behind-scenes-name-hiding-in-c.html

This is just one reason, but  NOT a strong reason, as Java overloading works across scopes contrary to C++. please see example from:

http://www.geeksforgeeks.org/does-overloading-work-with-inheritance/

Can someone tell me why Java work this way?

 

The work-around for name hiding

one is using directive

class Derived: public Base {

public:

using Base:f;

void f(int);

}

 

References:

http://www.programmerinterview.com/index.php/c-cplusplus/c-name-hiding/

http://thesyntacticsugar.blogspot.com/2011/10/behind-scenes-name-hiding-in-c.html

 

Leave a Reply

Your email address will not be published. Required fields are marked *