Search code examples
c++headernamespacesaliasdeclaration

C++ use included class from a header under another identifier


I'm facing an issue where a declared class name from an included (foreign) header file collides with the a declared class name of my own header file. But basically I want to compose my class with the included class. In Golang a solution would be to use a functionality called Import Declarations.

  • How can I achieve that:

    • without renaming my own declaration (or modifying the consumers of my own declaration)?
    • and without using inheritance (prefer composition over inheritance)?
    • and without altering the foreign code?
  • And what is the right terminology for this?

I've been searching already several threads and forums, but can't come up with a solution. What I tried till now (and what can be seen in the code beneath) is to surround the included header with a custom namespace. But this leads to nasty linking problems (see below), when I'm accessing methods of the included class. I'm kinda new to C++, so I'd be very happy about elaborated explanations, on how to achieve this.

The foreign header file ("some/sensor.h"):

class Sensor {
 public:
  Sensor(unsigned char a, unsigned char b);
 /*some definitions...*/
};

My declaration ("sensor.h"):

namespace Lib {
#include "some/sensor.h"
};

class Sensor {
 private:
  Lib::Sensor s; /* use foreign object as member */
 public:
  Sensor();
  void init(unsigned char p);
};

Receiving Errors like:

In function `Sensor::init(unsigned char)':
  undefined reference to `Lib::Sensor::Sensor(unsigned char, unsigned char)'
  /* ...and so on... */
collect2: error: ld returned 1 exit status

Solution

  • [Remark] For future readers:

    Please review the comments, as they reflect better the full picture of the answer. The following answer by @Baruch gives you a quick-fix to the situation. But as suggested in the comments this might be a poor design choice by authors of an external library.

    Original answer by @Baruch:

    You should put your code in a namespace, not the external code

    #include "some/sensor.h"
    
    namespace MyLib {
      class Sensor {
       private:
        ::Sensor s; /* use foreign object as member */
       public:
        Sensor();
        void init(unsigned char p);
      };
    }
    

    The link errors are caused by the fact that you essentially declared a new type, Lib::Sensor, which is not defined anywhere. The class defined in some/sensor.cpp is Sensor, not Lib::Sensor