Overriding

Overriding a function is no different than redefining one(which is the approach we have been using until now). An overridden function in a derived class has the same signature as the function it overrides in its base class. If we do not declare the base-class function as virtual, we can redefine that function. By contrast, if we declare the base-class function as virtual, we can override that function. We declare a virtual function by preceding the function’s prototype with the keyword virtual in the base class. For example,

   virtual void draw() const;

When a derived class chooses not to override a virtual function from its base class, the derived class simply inherits its base class virtual function implementation

Once a function is declared virtual, it remains virtual all the way down the inheritance hierarchy from that point, even if that function is not explicitly declared virtual when a class overrides it.

The virtual function has an implementation and gives the derived class the option of overriding the function

We aimed a base-class Point pointer at a derived-class Circle object, then invoked a member function print through that pointer. Recall that the data type of the handle determined which class’s functionality to invoke. In that case, the Point pointer invoked Point member function print on the Circle, despite the fact that the pointer was aimed at a Circle that has its own proper print function. Now, with virtual functions, the type of the object being pointed to, not the type of the handle, determines which version of a virtual function to invoke.

class Animal
 {
public:
void show()
{
cout << "This is Animal class";
 }
 };
class Tiger:public Animal
{
public:
void show()
 { 
cout << "This is Tiger class";
}
} 

OUTPUT:

This is Animal class
This is Tiger class  

Translate »