Virtual Functions in C++



Marking a function as virtual allows invoking the newest overriden definition of the function from the derived class even if the pointer is of base class

Without marking function virtual:

class Parent {
    public:
        void Show(){ cout<<"Showing from Parent!\n"; }  
};


class Child : public Parent {
    public:
        void Show(){ cout<<"Showing from Child!\n"; }  
};


int main()
{
    Parent * P = new Parent();
    Parent * C = new Child();
    
    P->Show();  // Showing from Parent!
    C->Show();  // Showing from Parent!
    
    return 0;
}

With marking function virtual:

class Parent {
    public:
        virtual void Show(){ cout<<"Showing from Parent!\n"; }  
};


class Child : public Parent {
    public:
        virtual void Show(){ cout<<"Showing from Child!\n"; }  
};


int main()
{
    Parent * P = new Parent();
    Parent * C = new Child();
    
    P->Show();  // Showing from Parent!
    C->Show();  // Showing from Child!
    
    return 0;
}