I'm implementing a simple hierarchy: System and Device would be two base classes. A System has Devices. Then I'd have a Network derived from System, which will have Computers. Computer is derived from both System and Device. And finally a Computer has various Devices like CPU, Memory etc. The reason Computer is a Device is because Network is a System and Systems store Devices. The reason Computer is a System is because it stores Devices (CPU, Memory etc.)
Anyway, my implementation so far:
class Device {
public:
explicit Device(unsigned property): property(property) {}
friend void swap(Device &first, Device &second) {
using std::swap;
swap(first.property, second.property);
}
Device& operator=(Device other) {
swap(*this, other);
return *this;
}
private:
Device() = default;
unsigned property;
};
class System {
public:
explicit System(const string &name): name(name) {}
friend void swap(System &first, System &second) {
using std::swap;
swap(first.name, second.name);
swap(first.devices, second.devices);
}
System& operator=(System other) {
swap(*this, other);
return *this;
}
protected:
void addDevice(Device b1) {
devices.push_back(b1);
}
private:
vector<Device> devices;
string name;
};
class Computer: public System, public Device {
public:
Computer(unsigned property, const string& name): System(name), Device(property) {}
Computer& addAddress(const string &address) {
addresses.emplace_back(address);
return *this;
}
Computer& addComponent(Device newDevice) {
System::addDevice(newDevice); //error
return *this;
}
private:
vector<const string> addresses;
};
class Network: public System {
public:
Network(const string& name): System(name) {}
Network& addComputer(Device newComputer) {
System::addDevice(newComputer); //no error
return *this;
}
};
class CPU: public Device {
public:
CPU(unsigned coreCount, unsigned frequency): Device(coreCount), frequency(frequency) {}
private:
unsigned frequency;
};
Computer's addComponent() has an error because cannot initialize object parameter of type System with an expression of type Computer
. I'm not entirely sure what that means since that function is called from a Computer class, which is a Device hence it should have access to the parent's addDevice(). The parameter the function has is a Device.
It's also confusing that my Network class, where the function addComputer() uses the same set of instructions has no error.
Could someone explain how my design is flawed?