简体   繁体   English

提供基类构造函数

[英]Providing a Base Class Constructor

Is it necessary to always provide your base class with a constructor? 是否有必要始终为您的基类提供构造函数? For example if I had the following base class, and then some derived classes. 例如,如果我有以下基类,然后是一些派生类。

class Animal
{
 public:

    //Is this constructor necessary?
    Animal(); 

    virtual ~Animal();
};

class Zebra: public Animal
{
 public:
    Zebra();
   ~Zebra();
};

class Elephant: public Animal
{
 public:
    Elephant();
   ~Elephant();
};

Assuming that I am creating Animal pointers and then dynamically allocating new Zebra and Elephant objects. 假设我正在创建Animal指针,然后动态分配新的Zebra和Elephant对象。 If I never intend to create an Animal object, then is there any actual need to explicitly create an Animal constructor? 如果我从不打算创建一个Animal对象,那么是否真的需要显式创建一个Animal构造函数?

You don't need to explicitly provide constructor. 您不需要显式提供构造函数。 A default one is generated (if you don't provide other constructor). 生成默认值(如果您不提供其他构造函数)。

so 所以

class Animal
{
public:

    virtual ~Animal();
};

is sufficient. 足够了。

Derived classes constructors would call Base class constructor (explicitly of implicitly). 派生类构造函数将调用Base类构造函数(显式地隐式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM