IBM Interview Question
Developer Program EngineersThe compiler will attempt to resolve any member function in the current class scope. Since a double can be converted to an int, the compiler finds a function foo() in the current class scope of Derived that matches. Therefore it chooses that function.
So basically, if the compiler finds a name of a function, it only looks in the current class scope for matches in parameter types (or looks for one where the parameter type given in the call can be converted to the type in the function declaration).
If the compiler does not find the function name in the current class scope, then and only then does it look in the parent class for a name that matches.
See below code snippet:-
#include <iostream>
using namespace std;
class Widget
{
};
class Base {
public:
virtual void foo(int f) {
cout << "Base Foo 1:: "<<f<<endl;
}
virtual void foo(double f) {
cout << "Base Foo 2:: "<<f<<endl;
}
void foo(Widget& w){
cout << "Calling Widget\n"<<endl;
}
virtual void func(){
cout<<"BASE"<<endl;
}
};
class Derived : public Base {
public:
void foo(int f) {
cout << "Derived Foo 1:: "<<f<<endl;
}
};
int main() {
Derived *d = new Derived;
Base *b = d;
cout << "Calling Base foo(double) through Base\n";
b->foo(3.14);
cout << "Calling Base foo(double) through Derived\n";
d->foo(3.14);
Widget w;
d->func(); // error
d->foo(w);
delete d;
getchar();
}
virtual overloading means the overriding of virtual function means the already existing base class virttual function we redefine in derived classes
- kumar August 15, 2011