Do you know the problem with overriding functions?

Submitted by: Administrator
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.
Submitted by: Administrator

Read Online C++ Virtual Functions Job Interview Questions And Answers