简体   繁体   中英

Do I need to reimplement all the constructor of a base class even if a derived class has no member variables?

Let's assume I have a base class

class Base
{
public:
    Base();
    Base(int i, double j);
    Base(int i, double j, char ch);

    virtual void print();

private:
    int m;
    double l;
    char n;
};

And I want to derive a class which overrides the print function but apart from that is exactly the same as the base class.

class Derived : public Base
{
public:
    void print();
};

Is there a way I can use all the constructors of the base class on the derived class without me rewriting all of them for the Derived class?

Since C++11, you may use using for that:

class Derived : public Base
{
public:
    using Base::Base; // use all constructors of base.

    void print() override;
};

Live demo

You can call the base class's constructors. So if you define Base as follows.

class Base
{
public:
    Base() {};
    Base(int i, double j) : m{i}, l{j} {};
    Base(int i, double j, char ch) : m{i}, l{j}, n{ch} {};

    virtual void print() { std::cout << "Base" << std::endl; };

private:
    int m;
    double l;
    char n;
};

Then you can have Derived have analogous constructors that use the Base constructors to initialize the inherited member variables.

class Derived : public Base
{
public:
    Derived() : Base() {}
    Derived(int i, double j) : Base(i, j) {}
    Derived(int i, double j, char ch) : Base(i, j, ch) {}

    void print() override { std::cout << "Derived" << std::endl; };
};

As an example

int main()
{
    Base b1{};
    Base b2{1, 2};
    Base b3{1, 2, 'a'};

    Derived d1{};
    Derived d2{1, 2};
    Derived d3{1, 2, 'a'};
}

You can do it the following way by means of delegating constructors and the using declaration as it is shown in the demonstrative program provided that your compiler supports C++ 2011. Otherwise you have to define the constructors yourself.

#include <iostream>

class Base
{
public:
    Base() : Base( 0, 0.0, '\0' ) {}
    Base(int i, double j) : Base( i, j, '\0' ) {}
    Base(int i, double j, char ch) : m( i ), l( j ), n( ch ) {}
    virtual ~Base() = default;

    virtual void print() const { std::cout << m << ' ' << l << ' ' << n << std::endl; }

private:
    int m;
    double l;
    char n;
};    

class Derived : public Base
{
public:
    using Base::Base;
    void print() const override { Base::print(); } 
};

int main()
{
    Derived( 65, 65.65, 'A' ).print();
}    

The program output is

65 65.65 A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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