Search code examples
c++dependenciesinclude

Is it possible to block #include in parent class from falling to child class


I'm new to C++ and don't really know what to google to find an answer to this, so I appologize if this is a stupid question.

I currently have a Book class, Inventory class, and Library class. The Inventory class needs access to the Book class and the Library class needs access to the Inventory class, but Library does NOT need access to the Book class. Is there a way to prevent the include for Book from falling through to the Library class?

class Book
{
};

.

#include "book.h"
#include <vector>

class Inventory
{
    std::vector<Book> Books;
};

.

#include "inventory.h"

class Library
{
    int main()
    {
        Book myBook; // I don't want this to be allowed
    }
};

Thanks all!


Solution

  • Is it possible to block #include in parent class from falling to child class

    No.

    However, it is possible to modify the parent class such that its definition does not depend on Book, and thereby its header does not need to include it, and therefore won't be transitively included into the child.

    The pattern to remove dependency on types of member objects is called PIMPL (sometimes called either "pointer to implementation" or "private implementation"). In very short, the idea is to not store the members directly, but by indirecting through an opaque pointer.