C++ inheritance design: avoid member duplication

  • A+

Let's assume that one has two C++ classes that support read-only and write-only operations on a file descriptor respectively.

class ReadFd {  public:   ssize_t read( /* */ ) {     // read from file_descriptor_   }  protected:   int file_descriptor_; };  class WriteFd {  public:   ssize_t write(/* */) {     // write to file_descriptor_   }  protected:   int file_descriptor_; }; 

Now suppose one would like to define a class ReadWriteFd that supports both read and write operations.

My question is how to design such read-write class to avoid code duplication?

I cannot inherit from both ReadFd and WriteFd because obviously I need just one file_descriptor_. The real situation that I encountered a bit more complicated but the concept here reflects it rather close.

Add a third class, base to both ReadFd and WriteFd, whose only purpose is to contain the descriptor variable (and possibly other things common to both reading and writing).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: