C++ Virtual Functions Question:
Download Questions PDF

Do you know the problem with overriding functions?

Answer:

Overriding of functions occurs in Inheritance. A derived class may override a base class member function. In overriding, the function names and parameter list are same in both the functions. Depending upon the caller object, proper function is invoked.

Consider following sample code:

class A
{
int a;
public:
A()
{
a = 10;
}
void show()
{
cout << a;
}
};

class B: public A
{
int b;
public:
B()
{
b = 20;
}
void show()
{
cout << b;
}
};

int main()
{
A ob1;
B ob2;
ob2.show(); // calls derived class show() function. o/p is 20
return 0;
}

As seen above, the derived class functions override base class functions. The problem with this is, the derived class objects can not access base class member functions which are overridden in derived class.

Base class pointer can point to derived class objects; but it has access only to base members of that derived class.

Therefore, pA = &ob2; is allowed. But pa->show() will call Base class show() function and o/p would be 10.

Download C++ Virtual Functions Interview Questions And Answers PDF

Previous QuestionNext Question
Can you please explain the difference between Overloading and Overriding?What is Static Binding?