I do have two classes: a reader and a writer. For both classes I have an abstract interface since the data source/target should be flexible:
class abstract_reader {
...
};
class concrete_reader : public abstract_reader {
DATATYPE m_data;
...
};
class abstract_writer {
...
};
class concrete_writer : public abstract_writer {
DATATYPE m_data;
...
};
The writer shall have both functionalities, to read and to write The implementation of the reading part of the concrete_writer is the same as the implementation of the concrete_reader. What would be a good way to combine these classes?
First, if it's just a
writer
, it shouldn't know how to read. What happens when you implement a writer to the screen? Still, having aReaderWriter
, in addition toReader
andWriter
, is a very reasonable choice, and that creates the same problem.The way I would do this is first, to define the
ReaderWriter
as an interface which inherits from bothReader
andWriter
:Note the virtual inheritance. This should generally be the default when you're extending interfaces. Once you've got that, you can (usually) use mixins for the implementation:
Client code which receives a
Reader*
can read; client code which receives aWriter*
can write; and client code which receives aReaderWriter
can do either. And of course, if the client has aReader*
, it can always try todynamic_cast
it to aWriter*
or aReaderWriter*
, and if the dynamic_cast succeeds, it can write as well.Edit: I forgot to mention: this technique is known as mixins.
Why would the writer want to know how to read? Maybe you should think about the 3rd class, incorporating BOTH reading and writing functionalities.
If you're convinced that it's OK, just derive the writer from both
abstract_reader
andabstract_writer
. As long as they are properly-implemented interfaces (no fields, for example), everything should work just fine.And oh, maybe it would be nice to incorporate templates (I've noticed the mysterious
DATATYPE
)But, as @Bartek pointed out, it seems odd to have a class named "writer" that also reads.
What you want is a little confusing, but there is a number of ways:
Personally, I would follow the last way, then you will have a full set of classes for reading-only, writing-only, and for doing both.