How to use the C++ classes in D

Overview

C++ classes are commonly used in D programs. D classes are incompatible with C++ classes, hence interfaces in D can be used to import C++ classes using extern(C++). The C++ program must have a function that creates an object of that class. To use C++ classes, we compile the .cpp file separately before the D program can use them.

Syntax

extern (C++) {
interface Math {
int multiply(int i, int j);
}
Math getMath();
}

As mentioned earlier, extern (C++) is used and a D interface is created which contains the methods from the C++ class to be used in its program.

Note: The C++ class that is to be used by D must have virtual methods in order to be used by D.

Example

main.d
base.cpp
extern (C++) {
interface Math {
int multiply(int i, int j);
}
Math getMath();
}
void main() {
Math a = getMath();
a.multiply(2,3);
}

Explanation

In the base.cpp file,

  • Line 5: We create a class that contains one public method of multiplication.
  • Line 14: We create function that creates the Math class object so that the D program can initialize an instance of this class.

In the main.d file,

  • Line 1: We use extern(C++) to indicate that code from C++ will be used in this program.
  • Line 2: We create an interface that contains the same member function as the C++ class.
  • Line 5: We add the getMath() function from C++ because it will be used to create an object of the C++ class.
  • Line 9: We create the C++ class object.
  • Line 10: We call the multiply function from the class.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved