Search code examples
c++access-specifier

C++'s version of Java's package-protection?


I'm working on the graphics code for a game library in Java. I made package called com.engine.graphics. In this package, I have a lower-level class called VertexArrayObject. This class is used by "client-level" classes that clients will use; however, I do not want to give clients access to VertexArrayObject, since it would only serve to complicate their understanding of my library. Thus, I gave VertexArrayObject the default access specifier; that way, only classes within com.engine.graphicshave access to it, and also tells clients that they do not need to know what it is.

Just like there is this standard convention for Java, I figured there must be some standard convention for C++ for dealing with this; however, my internet searches have yielded no results.

So, my question is, what is the convention? And if there isn't one, what is the best approach?


Solution

  • C++ does not have a notion of 'package' thus no 'package-protection' is technically possible. (There is a proposition for modules, but it will not be included even in the upcoming C++17 standard).

    There are many ways of hiding the class from external world or restricting access to it, on syntax level you can resort to:

    • nested classes which may be declared private (you should be familiar with them from Java, except they are "static" by default and cannot access non-static enclosing class members) link;
    • friend classes that can access any private members of the given class link;
    • friend functions if you want to restrict access to only certain functions, including member functions of another class;
    • private/protected inheritance where only the class members are aware of the inheritance link.

    Having a lot of friend classes and functions is a mess, but there is a reason for requiring explicit listing of those: they break the encapsulation principle.

    Finally, you can use either "private implementation" idiom (aka pimpl, aka opaque pointer) that consists in defining a visible class holding a pointer to the implementation class and forwarding all calls while the implementation class is defined in a separate cpp file or the façade design pattern.

    Chose whatever seems appropriate for the given class relation. Standard library tends to prefer nested classes while Qt, a popular graphic library, relies on pimpl.