Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance design: avoid member duplication

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.

like image 364
TruLa Avatar asked Dec 24 '22 07:12

TruLa


1 Answers

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

like image 175
Some programmer dude Avatar answered Dec 28 '22 06:12

Some programmer dude