Search code examples
c++classencapsulation

How to insulate class?


foo.h

class Foo {};

namespace {
    class Bar {};
   //...
}

foo.cpp

Foo foo; // Ok

Bar bar; // Ok, but I want Error!

How to hide (insulate) class Bar in *.cpp file?

i.e. I do not want to import the class Bar {} from *.h file into *.cpp file

Perhaps there is some kind of encapsulation technology for classes?


Solution

  • It's not clear exactly what you're asking for. If you only want Bar to be visible inside a particular .cpp file, that's pretty easy:

    foo.h:

    // add include guard here.
    class Foo {};
    

    foo.cpp:

    #include "foo.h"
    
    namespace {
        class Bar {};
    }
    
    Foo foo;
    
    Bar bar;
    

    Note that this restricts all visibility of Bar to foo.cpp though. Nothing outside foo.cpp will realize that it even exists.

    There's not really a way to make a class only visible inside a header though -- the whole point of a header is that you include it in one or more .cpp files, and when you do that, whatever it contains becomes visible inside that .cpp file.

    If that's what you think you want, chances are pretty good that you need to take a step back and tell us what you're really trying to accomplish. There's probably a way, but the way you're trying to go is almost certainly wrong. The basic division is that headers are for things that will be visible in general; anything that's private gets restricted to implementation (.cpp) files.