Why do we need to abstract classes instead of virtual ones?

I know there are so many questions on this topic. However, I could not figure out that it is necessary to use abstract classes instead of virtual ones. If I'm not mistaken, an abstract class is also implicitly a virtual class, and the only difference between the two is that the abstract method must be overridden in the child class. So why isn't the virtual classroom not enough? When do we need abstract classes rather than virtual classes?

+3


source to share


1 answer


First of all, there is no such thing as a "virtual classroom". I assume you meant to say a polymorphic class (with at least one virtual member function and of course a virtual destructor).

"Not necessary" for abstract classes (those that have at least one pure virtual member function), but they help to create interfaces that cannot be instantiated, but only provide a group of overridden member functions. This allows you to provide a generic base class to aid in polymorphism in cases where creating such a generic base class is impractical or contrary to the intent of the designers.



/**
 * 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 {}
};

      

+6


source







All Articles