Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use D classes from C++

Mohe Ud Din Sheikh


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);
Syntax for using D class in 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();


In the call.cpp file, we do the following actions:

  • Line 4: We declare a virtual function that overrides the class function.
  • Line 8: We declare a call function in which we pass class c and a pointer-type variable, p, as parameters.
  • Line 9: We use the p pointer to point to the show function overridden by the D show() function.

In the main.d file, we write the following:

  • Line 2: We use extern(C++) and then add the call () function which we used in the C++ program file.
  • Line 3: We used extern(C++)interface C to use the class defined within a D program file in our C++ program.
  • Line 8: We inherit the D program class from the C class defined in our C++ program.
  • Line 10: We use 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 command g++ call.cpp main.o -lphobos2 -pthread -o call && ./call to run the program.




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

View all Courses

Keep Exploring