7

I'm creating a static library in C++ to define a class that others can use in their code. However, a member of the class is of a type defined in a header file obtained from someone else, and I don't want to distribute the contents of this person's header file.

Here is the current public interface (interface.h):

class B {
    TypeToHide t;
    // other stuff ...  
};

class A {
    double foo();
    B b;
};

And here is the code that will be compiled into a static library (code.cpp):

double A::foo() {
    // ...
}

And here is the file whose contents I need to hide from public view (HideMe.h):

struct TypeToHide {
    // stuff to hide
};

What can I do hide the contents of HideMe.h? Ideally, I could just stick the entire struct from HideMe.h into code.cpp.

2 Answers 2

10

You can use the PIMPL idiom (Chesshire Cat, Opaque Pointer, whatever you want to call it).

As the code is now, you can't hide the definition of TypeToHide. The alternative is this:

//publicHeader.h
class BImpl;          //forward declaration of BImpl - definition not required
class B {
    BImpl* pImpl;     //ergo the name
    //wrappers for BImpl methods
};

//privateHeader.h
class BImpl
{
    TypeToHide t;  //safe here, header is private
    //all your actual logic is here
};
Sign up to request clarification or add additional context in comments.

2 Comments

OK, so using the PIMPL idiom is more or less that standard way of handling cases such as this?
3

Simpler than Pimpl, you can use a pointer to TypeToHide and a forward declaration for it:

class B {
    TypeToHide* t;
    // other stuff ...  
};

As long as you won't need knowledge about t's internal structure for the user's code, you won't have to expose it and it will stay safe in your library.
The code inside the library will have to know what TypeToHide is, but that's not a problem.

2 Comments

Thanks. What's the difference between PIMPL and your suggestion? (I'm new to the PIMPL idiom, so pardon my ignorance.)
Pimpl is a more structured paradigm claiming that you should usually avoid exposing the internal structure of your type. Instead, you should declare one pointer to the actual implementation (the P->impl) and only expose this pointer. For me, sometimes this principle is too aggressive, and I'm happy to leave some of the implementation public. In this question, for instance, you may only want to hide the implementation details of TypeToHide although according to Pimpl you should hide B itself behind the Bimpl type (as nicely demonstrated by Luchian).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.