What is a virtual function in D?

Introduction

In D, a virtual function helps redefine (override) the base class function by making this function usable with a different definition for the derived class.

We use the override keyword with the derived class function to override the base class function.

Syntax

override void func(){
//Defination of the function
}
Virtual function syntax

Example

import std.stdio;
class Parent
{
void func() {
writeln("Hello I am from Parent class");
}
}
class Child : Parent
{
override void func() {
writeln("Hello I am from Child class");
}
}
void main()
{
Parent p = new Child(); //Overide the parent func function
p.func();
}

Explanation

  • Lines 10–12: We declare a Child class from a Parent class in which we create a function func. We use the override keyword to override the Parent class function.
  • Line 19: We override the Parent class object p with the Child class.
  • Line 20: We call the func function, which calls a function from the Child class.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved