c++interfaceaggregationdelegation

Simpler forwarding of contained object


I have a proprietary file format definition that contains a header format:

class Header
{
  public:
   uint32_t  checksum;  
   uint16_t  impedance;
   uint16_t  type_of_data;  
   uint32_t  rows_in_file;
};

class MyFile
{
    Header   file_header;
};

If I want to provide an interface to the header elements, I would include in the MyFile class:

class MyFile
{
  public:
    uint32_t  get_checksum() const {return file_header.checksum;};
    uint16_t  get_impedance() const {return file_header.impedance;};
    uint16_t  get_type_of_data() const {return file_header.type_of_data;};
    uint32_t  get_rows_in_file() const {return file_header.rows_in_file;};

  private:
    Header   file_header;
};

Is there a method of delegating to the contained object other than duplicating the interface?
Note: The header contains a lot more data and the data is not public (made public for simplicity in this question).
Note: The actual interface of the Header comprises of getters and setters.

If I use inheritance, I can get the interface of the Header object without any duplication; but the MyFile is not a Header, it contains a Header.


Solution

  • From what it sounds it seems like a simpler getter will do:

    class MyFile
    {
      public:
        Header header() { return file_header; }
    };
    

    Another option is to overload operator->() so you can indirect into the header properties (remove const as needed):

    class MyFile {
      public:
        Header const* operator->() const { return &file_header; }
    };
    

    Then you can access properties by doing myFile->checksum for instance.