virtual

Summary

The virtual modifier is used to declare a method as a virtual method that can be overridden by derived classes using the 'override' keyword.

Syntax

virtual member

Parameters

member
The member to make 'virtual'.

Description

The virtual modifier is used to declare a method or property as a virtual method or property, respectively. Virtual methods can be overridden using the override or final modifier.

By default, methods are non-virtual and are resolved at compile time. If a derived class has a method with the same name as its base class, this is known as shadowing (or method hiding) and gets resolved at compile time. However, virtual methods are resolved at runtime. At runtime, when a virtual method is called, the runtime type of the invoking object is examined, and the overridden method of the most derived class is called. If no overridden methods are available, the original virtual method is invoked.

A method cannot be overridden if:

  • It is not virtual or abstract
  • It is static
  • It has a different access modifier
  • It has a different return type, parameter type, parameter order, or method signature

Examples

Iterating Array of Objects and Calling Overridden Functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import System;
 
class Shape
{
    public virtual double area() {
        return 0;
    }
}
 
class Rectangle : Shape
{
    private int length, width;
 
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }
 
    public override double area() {
        return length * width;
    }
}
 
class Triangle : Shape
{
    private int base, height;
 
    public Triangle(int base, int height) {
        this.base = base;
        this.height = height;
    }
 
    public override double area() {
        return (base * height) / 2;
    }
}
 
Shape[] shapes = [ new Rectangle(5, 5), new Triangle(3, 4) ];
foreach(Shape shape in shapes) {
    Console.log(shape.area());
}
 
// Output:
// 25
// 6

See Also

Share

HTML | BBCode | Direct Link