informa
/
1 MIN READ
Featured Blog

Accessing privates without 'friend'(c++)

A neat way to access privates from one class to another, without direct inheritance or friend.

[ From Pompi Dev Blog

Here is a neat little way I found to make one class access the privates of another class, without using friend or direct inheritance. Take a look at this code:

class A {
    public:
        class Observer {
             protected:
                 int GetPrivate(A & a) {return a.ValueA;};
        };
    private:
        int ValueA;
};
class B: public A::Observer {
    public:
        void Foo (A & a) {
             Do something with GetPrivate(a);
        }
};

 

Class B cannot access the privates of class A directly, but it inherits a subclass of A that can access the privates of A given as a parameter. Since I have just tried this "pattern" recently, I am not sure what is the direct benefit of this.

I believe a benefit can be in the sense of making a programmer's life easier. Programming languages play several parts. They provide us powerful functionality, but they also suppose to give us ease of use. You can program anything on assembly, but it would be really difficult to write a big game in assembly. If you do not expose privates via a getter, you give the programmer one less method to think about when he need to use the class's instance for something.

Can you think how you would use this "pattern"? Do you think there is no use for it? Tell me what you think.

 

Latest Jobs

Treyarch

Vancouver, BC, Canada
5.8.23
Producer

Bladework games

Remote (United States)
5.18.23
Senior Gameplay Engineer

University of Canterbury

Christchurch, Canterbury, New Zealand
5.17.23
Academic in Game Arts and Animation

Fred Rogers Productions

Hybrid (424 South 27th Street, Pittsburgh, PA, USA
5.19.23
Producer - Games & Websites
More Jobs   

CONNECT WITH US

Explore the
Advertise with
Follow us

Game Developer Job Board

Game Developer

@gamedevdotcom

Explore the

Game Developer Job Board

Browse open positions across the game industry or recruit new talent for your studio

Browse
Advertise with

Game Developer

Engage game professionals and drive sales using an array of Game Developer media solutions to meet your objectives.

Learn More
Follow us

@gamedevdotcom

Follow us @gamedevdotcom to stay up-to-date with the latest news & insider information about events & more