Ofer Magen Ofer Magen - 1 month ago 5
C++ Question

Encapsulation in header files

I have a header file with 2 classes. class A (which is a very big class) and class B that inherits class A. I don't want people to be allowed to create objects of class A or even be able to see its static members. They should only to work with class B. What is the best way of doing that.

(Generally speaking A is a "helper class")


To restrict the creation of the class, make the constructor of class A private and declare class B as a friend class. This way only B can instantiate A.

class B;
class A
    friend class B;

The same applies to methods (static or not): make them all private and the friend statement will allow B to access A's members.

Edit: works with protected as well.