Reputation: 566
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?
Upvotes: 4
Views: 296
Reputation: 311156
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
Upvotes: 1
Reputation: 218323
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;
};
Upvotes: 10
Reputation: 118021
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'};
}
Upvotes: 1