10
Reply

What is Virtual keyword?

Samir Bhogayta

Samir Bhogayta

9y
1.9k
0
Reply

    We use Virtual keyword in the base class method so that we can achieve Runtime polymorphism. or you can better say Late Binding. you can override the base class method in the derived class.

    If a base class method is to be overriden, it is defined using the keyword virtual

    when member functions in both base and derived class is having same function name then the function in base class declaired with the keyword "virtual".

    virtual keyword is used for achieving method overriding. in derived class, we want to override the base class method then it should be declared virtual in base class

    Nice explanation Anil Kumar Murmu.

    @ Barkha Gupta. Having the same name in base and derived is the result of thought process. However the main thought is if we want any method to be overridden in child classes, then we declare the method as virtual.

    using virtual keyword member can be overriden in a child class.

    Let us understand what virtual in layman term means. It means "not physically existing". Now lets assume one of the scenario, if we have a function say Add(int firstNumber, int secondNumber); it is present both in parent class as well as child class. Now the rules in inheritance says if we create an instance of Child class, it has access to all public data members/functions in Child class as well as parent class. Now if we compile this code in VS, then we will get a warning to use New key word in Child class Add() method definition. This is the concept of method hiding. However, if suppose we remove the implementation of Add method in child class then it will call the Parent class method. That is why we should use Virtual keyword. Again we have to bid with few of OOPs rules: if any method is virtual in parent class then in child class while implementing the same(which is not mandatory) should be marked as override.

    This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events.

    The "Virtual" keyword means that the method and variable are marked as virtual in base class you can override in derived class and change the definition of that method, its useful when you perform the Late Binding (Dynamic Binding).