What's the difference between virtual function instantiations in C++?

后端 未结 8 2016
栀梦
栀梦 2021-01-25 07:30

What\'s the difference between the following two declarations?

virtual void calculateBase() = 0;  
virtual void calculateBase();

I read the fir

8条回答
  •  忘掉有多难
    2021-01-25 07:56

    The first one is a "pure virtual" - it will make the class abstract, attempting to instantiate it will result in compiler errors. It is meant to be used as a base class where the derived class implements the necessary behaviour by implementing the pure virtual function. You do not have to implement the function in the base class, though you can.
    This is a pattern often used for two design patterns:

    • The "template method" design pattern, where the base class implements a structure around a function call, but the details of the function call must be filled in by the derived class, and
    • The "interface" design pattern, because C++ doesn't have the interface keyword. Abstract base classes, ideally with only pure virtual functions and no member data, are the C++ way of defining interfaces.

    The second declaration is just an ordinary virtual member function declaration. You will get compiler errors if you fail to implement the member function in the base class. It is still virtual which implies that it may be useful to override the behaviour in a derived class.

提交回复
热议问题