The D programming language is compatible with C++, which allows us to connect the two by simply using external(C++) interface C
. We can use classes defined in D program files in our C++ programs.
To use the class in our C++ program, we need to compile the D program file separately, and by using this compiled file, we can use the class in D in our C++ program.
Let's look at the syntax.
extern (C++) void call(C);
To use the D class, we have to use extern(C++)
. Then we add the call()
function, the function we used in the C++ program file.
import std.stdio ; extern (C++) void call(C); extern (C++) interface C { void show(); } //inheriting D class from c++ class class D : C { extern (C++) void show() { writeln("I came from D class"); } } void main() { //Declaring d obeject of d class D d = new D(); call(d); }
In the call.cpp
file, we do the following actions:
virtual
function that overrides the class
function.call
function in which we pass class c
and a pointer-type variable, p
, as parameters.p
pointer to point to the show
function overridden by the D show()
function.In the main.d
file, we write the following:
extern(C++)
and then add the call ()
function which we used in the C++ program file. extern(C++)interface C
to use the class defined within a D program file in our C++ program.extern(C++)void show()
, in which we use extern(C++)
to show that it's from an external C++ program file. We use void show()
to inherit the show member function of that program, g++ -c sum.cppdmd main.d sum.o -L-lstdc++ && ./main
.Note: To run this program locally, we have to compile the D file separately by using the
dmd -c main.d
command in the terminal, and after the compilation, we need to use the commandg++ call.cpp main.o -lphobos2 -pthread -o call && ./call
to run the program.
RELATED TAGS
CONTRIBUTOR
View all Courses