Why do I have to call PoweredDevice in SuperCopier's constructor? Copier's constructor already initialize when a Copier object is directly created.
Is not there any easy way to encapsulate Copier? (just use it's constructor and do not care it's bases.)
Below code is from http://www.learncpp.com/cpp-tutorial/128-virtual-base-classes/ with little modifications.
#include <iostream>
class PoweredDevice
{
public:
PoweredDevice(int power)
{
std::cout << "PoweredDevice: " << power << '\n';
}
};
class Scanner: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class
{
public:
Scanner(int scanner, int power)
: PoweredDevice(power) // this line is required to create Scanner objects, but ignored in this case
{
std::cout << "Scanner: " << scanner << '\n';
}
};
class Printer: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class
{
public:
Printer(int printer, int power)
: PoweredDevice(power) // this line is required to create Printer objects, but ignored in this case
{
std::cout << "Printer: " << printer << '\n';
}
};
class Copier: public Scanner, public Printer
{
public:
Copier(int scanner, int printer, int power)
: PoweredDevice(power), // PoweredDevice is constructed here
Scanner(scanner, power), Printer(printer, power)
{
}
};
class SuperCopier: public Copier
{
public:
SuperCopier(int scanner, int printer, int power)
: PoweredDevice(power),//This is the line I want to get rid of
Copier(scanner, printer, power)
{
std::cout<<"Super copier constructed\n";
}
};
int main()
{
Copier copier(1,2,3);
SuperCopier superCopier(4, 5, 6);
}
Output:
PoweredDevice: 3
Scanner: 1
Printer: 2
PoweredDevice: 6
Scanner: 4
Printer: 5
Super copier constructed