Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")

like image 593
Ofer Magen Avatar asked Jun 19 '26 07:06

Ofer Magen


1 Answers

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
{
private:
    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.

like image 95
Fabien Bouleau Avatar answered Jun 21 '26 22:06

Fabien Bouleau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!