C++ Abstract Class: constructor yes or no?

2019-01-30 03:52发布

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 that provides the following example:

class Employee {
   public:
       Employee(const char*, const char*);
       ~Employee();
       const char* getFirstName() const;
       const char* getLastName() const;


       virtual double earnings() const=0  // pure virtual => abstract class
       virtual void print() const

  private:
       char* firstName, lastName;
};

If the class is abstract why we have a constructor? It uses this class later (Boss is public derived from Employee):

void Boss::Boss (const char* first, const char* last, double s)
     : Employee (first, last)

8条回答
等我变得足够好
2楼-- · 2019-01-30 04:43

To initialize firstName and lastName. Otherwise you will have to write a code to initilze them in each derived classes' constructors

查看更多
混吃等死
3楼-- · 2019-01-30 04:45

"An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration."

regarding:

void Boss::Boss (const char* first, const char* last, double s)
     : Employee (first, last)

first and last are defined in the base class, therefore, in order to initialize them, we need to make a call to the constructor of the base class : Employee (first, last)

查看更多
登录 后发表回答