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 functionp.func();}
Explanation
- Lines 10–12: We declare a
Childclass from aParentclass in which we create a functionfunc. We use theoverridekeyword to override theParentclass function. - Line 19: We override the
Parentclass objectpwith theChildclass. - Line 20: We call the
funcfunction, which calls a function from theChildclass.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved