Avoiding Defining a pure virtual function in c++ i

2019-08-15 00:38发布

问题:

Do we have to compulsorily define a pure virtual function in c++ in the immediate derived class ? Or can we just avoid it so that we can define it only in concrete classes ? How is this achieved ?

回答1:

No one forces you to implement pure virtual functions, so you don't have to. Your class will just be abstract. In a derived class, just leave the declaration out or re-declare it as virtual pure.

struct Base
{
   virtual void foo() = 0;
};

//this is OK, X is abstract
struct X : Base
{
};

//this is also OK, redundant, and Y is abstract
struct Y : Base
{
   virtual void foo() = 0;
};


回答2:

There's absolutely no requirement to ever define any pure virtual functions in the class until you begin to create actual objects of that class.

Abstract classes are intended to serve as bases for other classes. The abstract class hierarchy can be arbitrarily deep, meaning that you are not required to define pure virtual methods in the immediate descendant.



回答3:

If there's some virtual pure method not implemented then the derived class is abstract. You must implement the method in some derived class if you want to instantiate it.