Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d

What is a virtual function in D?

Mohe Ud Din Sheikh

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();
}
Program example

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.

RELATED TAGS

d

CONTRIBUTOR

Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring