Does the whole constructor of the base class need to be redefined, even if the derived class does not have member variables?

Suppose 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 get a class that overrides the print function, but except that it is exactly the same as the base class.

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

Is it possible to use all the constructors of the base class in a derived class without having to rewrite them all for the Derived class?

+4
source share
3 answers

Since C ++ 11, you can use usingfor this:

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

    void print() override;
};

Live demo

+10

You can call base class constructors. Therefore, if you define Baseas 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;
};

Derived , Base -.

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; };
};

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

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

You can do this as follows by delegating constructors and declaring use, as shown in the demo program, provided that your compiler supports C ++ 2011. Otherwise, you must 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();
}    

Program exit

65 65.65 A
+1
source

All Articles