C++ hiding inherited class?

653 Views Asked by At

I am trying to hide the inclusion of a third party file in a main class header in a library I wrote, from the executables that link it. What I mean is:

I have a library that I wrote that defines class A. Class A inherits from class B (which is defined in a third party library). Example:

// In A.h
#include “B.h”
class A : public B
{
    A* something(A* val);
}

// In A.cpp
A* A::something(A*val)
{
    // Do something
    return val;
}

The header file for class B makes some changes to the environment that are ideal for my library, but are harmful to any executable that links my library. Someone pointed me to Opaque pointers as a potential solution, though I cannot see how I could use them to hide “B”.

Does anyone know a way to hide the inclusion of B.h? For solutions, C++11 is OK, but linking to additional dependancies (like boost) is not an option.

2

There are 2 best solutions below

1
On BEST ANSWER

One normal way to hide the "implementation" in C++ world is by Pimpl/Handle-body/bridge idiom.

Instead of exposing your class A to user of your API, have a handle class that expose only what you want:

In A.h

class AImpl;  // forward declaration

class A {
private:
  AImpl* impl;

public:
  foo();
  bar();
}

Then have your actual implementation in another file:

AImpl.h

#include <B.h>

class AImpl: public B {
private:
public:
  foo();
  bar();
  somethingThatYouDontWantToExpose();
}
3
On

The way to use opaque pointers is to forward declare the classes you need to use so you don't need to include their definitions. Since you're not including B.h the clients of your library won't be polluted by their definitions.

// In A.h
class B;

class A
{
private:
    B* opaque;
};