Reputation: 585
I know there are so many questions about on this topic. However, I couldn't understand the exact need for using abstract classes instead of virtual ones. If I am not mistaken, an abstract class is also implicitly a virtual class and the only difference between them is that the abstract method has to be overridden in child class. So, why isn't virtual class enough? In which cases do we exactly need abstract classes rather than virtual classes?
Upvotes: 4
Views: 180
Reputation: 385295
First of all, there is no such thing as a "virtual class". I'll presume you meant to say a polymorphic class (with at least one virtual member function, and certainly a virtual destructor).
There is no "need" for abstract classes (those with at least one pure virtual member function), but they aid in creating interfaces that cannot be instantiated, but only provide a bunch of overrideable member functions. It allows you to provide a common base class to aid in polymorphism, in cases where instantiating such a common base class would serve no purpose or would go against the grain of designers' intent.
/**
* Instantiating `IType` cannot serve a purpose; it has
* no implementation (although I _can_ provide one for `foo`).
*
* Therefore, it is "abstract" to enforce this.
*/
struct IType
{
virtual void foo() = 0;
virtual ~IType() {}
};
/**
* A useful type conforming to the `IType` interface, so that
* I may store it behind an `IType*` and gain polymorphism with
* `TypeB`.
*/
struct TypeA : IType
{
virtual void foo() override {}
};
/**
* A useful type conforming to the `IType` interface, so that
* I may store it behind an `IType*` and gain polymorphism with
* `TypeA`.
*/
struct TypeB : IType
{
virtual void foo() override {}
};
Upvotes: 6