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.
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.
extern (C++) {interface Math {int multiply(int i, int j);}Math getMath();}void main() {Math a = getMath();a.multiply(2,3);}
In the base.cpp
file,
Math
class object so that the D program can initialize an instance of this class. In the main.d
file,
extern(C++)
to indicate that code from C++ will be used in this program.getMath()
function from C++ because it will be used to create an object of the C++ class.multiply
function from the class.Free Resources