Q) What is the output of following C++ program?
class Base{
public:
void f(){
cout<<"Base::f()"<<endl;
}
};
class Derived:public Base{
public:
void f(){
cout<<"Derived::f()"<<endl; } }; int main(){ Base *d = new Derived(); d->f();
return 0;
}
- Base::f()
- Derived::f()
- Base::f() Derived::f()
- Compiler error
Answer: 1
If we create an object of derived class, keep its address of it in base class pointer and make a call of the function f() which is in both class, then base class version will be called. If in the base class, we make the f() virtual as “virtual void f()”, then derived class version will be called.