What is Virtual Method
In object-oriented programming, a virtual function or virtual method can be changed by an overriding member in a derived class by a method with the same signature. In order to create virtual function, precede the method's declaration in the base class with the "virtual" modifier.
Calling Base Class !!
Calling Derived Class !!
When calling a virtual method, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. From the above example, when we call first time Display(), compile time type is "baseClass" and runtime type also is "baseClass". When second time call Display(), compile time type is "baseClass" and runtime type is "derivedClass".
From the above example we can understand that with "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object. More about.... Early Binding and Late binding
Virtual methods are similar to abstract methods in base classes except their implementation on derived classes is optional. More about.... Abstract Classes
Note: By default, methods are non-virtual. You cannot override a non-virtual method.
- What is a Class?
- What is an Object?
- Constructors and Destructors
- What Is Inheritance ?
- What are the different types of inheritance ?
- What are Access Modifiers ?
- Why Classes cannot be declared as Protected?
- Can we declare private class in namespace
- Difference between Classes and Structures
- Can we use pointers in C# ?
- Why abstract class can't create instance
- Can you prevent your class from being inherited
- Difference between method Overloading and Overriding
- Difference between Early Binding and Late binding
- What is nested class
- What is partial class ?
- Difference between class and object
- What is Data Encapsulation?
- Object Based Language and OOPs