Easy Tutorial
❮ Verilog2 Timing Check Intelligent Dev Ops ❯

What is a Virtual Method?

Category Programming Techniques

Content

A virtual method can have an implementation body. If an instance method declaration contains the virtual modifier, it is called a virtual method. After using the virtual modifier, it is not allowed to have static, abstract, or override modifiers.

Example of a virtual method in a simple factory pattern code:

// For the result after calculation
public virtual double GetResult()
{
    double result = 0;
    return result;
}

It can be seen that there is a method called GetResult() in this class, which contains a virtual modifier. This modifier indicates that the derived classes of this base class can override this method. The function of the GetResult() method is to output the statement "This is a virtual method!" to the console.

The implementation of a virtual method can be replaced by a derived class. The process of replacing the implementation of an inherited virtual method is called overriding the method; in a virtual method call, the type of the instance at runtime determines which implementation of the method is to be called.

The Difference Between Abstract Methods and Virtual Methods

In simple terms, an abstract method is one that needs to be implemented by the subclass. A virtual method is already implemented and can be overridden by the subclass, or it can be left unoverridden, depending on the requirements.

Both abstract and virtual methods can be overridden by derived classes.

Summary

In general, a virtual method is a method whose declaration contains the virtual modifier. This is a preliminary understanding for now, and I will supplement it with a deeper understanding later, and also welcome everyone to share their own understanding.

** Click to Share Notes

Cancel

-

-

-

❮ Verilog2 Timing Check Intelligent Dev Ops ❯