Thursday, December 31, 2009

Few words on Function Overloading

 struct A { int foo(){std::cout<<"No Arg";} };
 struct B { int foo(int a){std::cout<<a;} };

 struct C : A, B
 //To Solve the error, uncomment NEXT LINE
 //using A::foo; using B::foo;

 int main()
 C c;; //Throws an error
 return 0;

For, folks who think its simple Function Overloading, ITS NOT!!
Also, there is no syntax error ofcoarse.... :D

But, it feels that it should not throw an error.

Why is there an error?
Because in looking up the name, it finds functions in two different base class scopes. In this situation, the lookup is ambiguous - they don't overload each other.

To Solve!!
A fix would be to use a using declaration for each member name. Lookup will find names in the scope of C++ and don't lookup further.
Now, the call would find two functions, do overload resolution, and find that the one taking int will fit.

Powered by ScribeFire.

No comments:

Post a Comment