Explain the problem with overriding functions

Explain the problem with overriding functions.

- Overriding of functions occurs in Inheritance. A derived class may override a base class member function. In overriding, the function names and parameter lists are same in both the functions. Depending upon the caller object, proper function is invoked.
- Consider the 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.
Overloading vs. overriding
Overloading vs. overriding - Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. ....
What is virtual destructor? What is its use?
What is virtual destructor? What is its use? - If the destructor in the base class is not made virtual, then an object that might have been declared....
What is object slicing? - C++
What is object slicing? - When a Derived Class object is assigned to Base class, the base class' contents in the derived object...
Post your comment
Discussion Board
Error
this program had a error-Declaration incorrectly terminated
Anushree Paul 10-17-2015