base class ‘class Base’ should be explicitly initialized in the copy constructor

内容纲要

项目中编译选项开启了 -Wextra 之后出现了如下警告:

“base class 'class xxx' should be explicitly initialized in the copy constructor”

意思是在子类的拷贝构造函数中应该显示指明父类。

例子如下:

#include <iostream>

class Base
{
    public:
        Base() {
            std::cout << "base ctor .." <<std::endl;
        };
        Base(Base const &){
            std::cout << "base copy ctor." << std::endl;
        };
        void func(){
            std::cout << "base func." << std::endl;
        };
};

template <int value>
class Derived : public Base
{
    public:
        Derived() = default;
        Derived(Derived<value> const &other);
};

template <int value>
Derived<value>::Derived(Derived<value> const &right)
//    : Base(right)
{
     std::cout << "Derived copy ctor." << std::endl;
}

int main()
{
    Derived<5> d5;
    Derived<5> d5b(d5);
    d5b.func();
}

输出结果:

base ctor ..
base ctor ..
Derived copy ctor.
base func.

https://godbolt.org/z/5d4xMbG6T
把 35 行注释后代码解除后,可解除警告。

为什么会告警呢?大部分情况,我们可能期望从子类中调用父类的拷贝构造函数,但是很容易忘掉,如果不指定,就调用父类默认构造了,与期望有差异了。

打赏作者