Abstract class vs Interface in C++
It is often confusing when it comes to interface and abstract class in C++. There are no keyword to define an interface and abstract classes in C++, as in other programming languages like Java or C#.
Yet, the use of interface and abstract class can be achieved in C++ similar to other languages.
First let us compare the concept of interface and abstract class
- Interface class does not have any method implementation. It only has method declarations and the class that implements an interface implement the methods.
- Interface does not have defined variables. It does exist in java but then the variables are stated as final and static.
- The class which implements an interface must implement all the methods of the interface.
- Abstract class can have variable declaration and method implementation/declarations. Moreover one can inherit the abstract class without implementing the abstract methods.
- An abstract class cannot be instantiated but rather inherited by another class. Instantiating and abstract class will give compilation error.
Before looking at how we define abstract and interface, lets understand what is a virtual and a pure virtual method in C++.
A virtual method in C++ is a method which is to be redefined in the derived class, using the virtual keyword tells the compiler to perform dynamic linkage or late binding on the method.