How to declare an interface in C++? Pure virtual functions and abstract classes
Hi everyone! I recently started learning C++ after Java, and I'm having trouble declaring interfaces. In Java, I'm used to writing `interface MyInterface { void doSomething(); }`, and any class can implement it. \n\nBut in C++, I can't find an equivalent of the `interface` keyword. I tried making a class with regular virtual functions, but the compiler complains that the class cannot be instantiated if the function is not pure virtual. Here's what I wrote:\n\n```cpp\nclass IShape {\npublic:\n virtual double area(); // Error: not pure virtual\n virtual void draw(); // Also error\n};\n```\n\nThen I added `= 0`, and the code compiled:\n\n```cpp\nclass IShape {\npublic:\n virtual double area() = 0;\n virtual void draw() = 0;\n};\n```\n\nBut I'm not sure if this is the correct way.
No answers yet.
Log in to leave an answer
Blogs