Answer the question
In order to leave comments, you need to log in
How to connect a specific heir to a specific parent?
Hello. Tell me please.
There are 2 classes. ComPort and its derived class Device.
There are 2 objects of the ComPort type: COM1, COM2, which contain their own settings (some parameters), and 2 objects of the Device type: Dev1 and Dev2.
The Dev1 and Dev2 objects use the inherited write function to write data to one or another com port.
How can I make Dev1 use the parameters of the COM1 object only, and Dev2 only use the parameters of COM2? Those. how to specify a hard link - a specific parent - a specific child? For if I try to use the parent's parameters in the heir, then I get their default values, which are set through the class constructor, and I need to use the baud rate values set for the parents, the physical port number, and so on. Thank you.
Answer the question
In order to leave comments, you need to log in
This will separate the ComPort and Device classes.
And when creating a Device object, pass the ComPort object to it.
Inheritance in your task is not needed.
Well, something like this (spherical code in a vacuum):
or
if it generally happens. I can't say anything specific without class headers.
In general, there is an assumption that you do not distinguish an instance of an object from its description.
And if with inheritance, then COM1 and COM2 are clearly superfluous here - all actions must be done through Dev.
An inheritance relationship in the real world is best described by the word "is". Each ComPort is a device, but the opposite is not true (devices are probably different, otherwise it is not clear why such a class at all). So Device must be the base class.
Next, regarding the relationship of two instances. Each instance of the ComPort class is already a Device thanks to inheritance. The device's write function can be virtual and abstract (=0 without its own implementation). In ComPort, it will override with a specific implementation for the port.
Thus you can have:
Device * d = new ComPort(setting1, setting2);
d.write(data);
std::vector<Device *> ds;
ds.push_back(new ComPort(setting1, setting2));
ds.push_back(new UsbPort(setting3, setting4));
for (auto d : ds)
d->write(data);
</code
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question