Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual keyword use in C++

Tags:

People also ask

What is the use of virtual keyword?

The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class.

What is virtual keyword with example?

A virtual keyword is an indication to the compiler that a method may be overridden in derived classes. Coming to the C# perspective, the virtual keyword is used to modify the declaration of any property, method or event to allow overriding in a derived class.

What is the use of virtual keyword in C Plus Plus?

A virtual function in C++ is a base class member function that you can redefine in a derived class to achieve polymorphism. You can declare the function in the base class using the virtual keyword.


I understand that C++ implements runtime polymorphism thorugh virtual functions and that virtual keyword is inherited but I don't see use of virtual keyword in derived class.

e.g. In below case even if you dropped virtual keyword in derived class still ptr->method() call goes to derived::method. So what extra this virtual keyword is doing in derived class?

#include<iostream>

using namespace std;

class base
{
public:
    virtual void method()
    {
        std::cout << std::endl << "BASE" << std::endl;
    }
};

class derived: public base
{
public:
    virtual void method()
    {
        std::cout << std::endl << "DERIVED" << std::endl;
    }
};

int main()
{
    base* ptr = new derived();
    ptr->method();
    return 9;
}