C++ Abstract Class: constructor yes or no?

后端 未结 8 1871
轮回少年
轮回少年 2020-12-04 08:45

A class with one (or more) virtual pure functions is abstract, and it can\'t be used to create a new object, so it doesn\'t have a constructor.

I\'m reading a book t

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 09:07

    You're correct when you say that a class that has a pure virtual function is abstract and can't be instantiated. But you're wrong when you say that it can't have a constructor.

    Indeed, as your example show, an abstract class can have private members, that may be used by member functions of this class. And these members must be initialized. A constructor is a way to do that (e.g. with an initialization list in the derived class, as your second sample shows), better in my opinion than an init() function for example.

    Editing my comment in the answer: An abstract class can have member variables and potentially non-virtual member functions, so that every derived class from the former implements specific features.

    Then, the responsibility for the initialization of these members variables may belong to the abstract class (at least always for private members, because the derived class wouldn't be able to initialize them, yet could use some inherited member functions that may use/rely on these members). Thus, it makes it perfectly reasonable for abstract classes to implement constructors.

提交回复
热议问题