Virtual base class data members

前端 未结 5 2087
我在风中等你
我在风中等你 2021-01-05 04:30

Why it is recommended not to have data members in virtual base class?

What about function members? If I have a task common to all derived classes is it OK for virtua

5条回答
  •  一生所求
    2021-01-05 05:16

    All-abtract base classes that are used to simulate interfaces in C++ should not have data members - because they are describing an interface, and instance state is an implementation detail.

    Other than that, base classes containing virtual functions may well have data members. The usual rules apply, though:

    • make them as hidden as possible, and use getters and setters if you need to preserve class invariants.
      (There's a loophole in here: if there's no invariant associated with the member, i.e. it may assume any possible value at any given time, you might make it public. However, this denies a derived class adding an invariant.
    • Design for inheritance: the contract of your class should define the responsibilities and possibilities of a derived class, what it needs/can overwrite for what purpose.

提交回复
热议问题