I
I
Ilia Zhitenev2016-02-09 13:19:33
OOP
Ilia Zhitenev, 2016-02-09 13:19:33

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

4 answer(s)
P
Peter, 2016-02-09
@ilyazh

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.

A
Anatoly Medvedev, 2016-02-09
@balamyt92

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.

R
res2001, 2016-02-09
@res2001

And if with inheritance, then COM1 and COM2 are clearly superfluous here - all actions must be done through Dev.

T
tsarevfs, 2016-02-09
@tsarevfs

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

in this case, write will be called with the desired settings (setting1, setting2).
Moreover, this approach will allow you to use different devices uniformly:
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 question

Ask a Question

731 491 924 answers to any question