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.