Overflowh
Overflowh

Reputation: 1114

C++ Private data member access: good practices

Suppose we are in this condition:

class C {
    int a, b;
public:
    C(int aa, int bb) { 
        setA(aa);
        setB(bb);
    }
    void setA(int aa) { a = aa; }
    int getA() { return a; }
    void setB(int bb) { b = bb; }
    int getB() { return b; }
    C add(const C c1, const C c2);
};

If in add() I need to access data members, which is the best way to do it? I should use the access functions set and get (created for the client programmer), or I can simply use data members as themself (c1.a, c1.b, c2.a, c2.b) since I am the class designer?

Upvotes: 0

Views: 1612

Answers (4)

s3rius
s3rius

Reputation: 1452

In this particular example I'd simply use the variable names directly.

But there are similar situations where the getters/setters are of much more use.

For example, when the setter (or getter) function is more complicated than just the trivial x = y:

void SetA(int aa){ //a between 0 and 100
    a = std::max(0, std::min(aa, 100));
}

Or when you want to subclass C and overload the getter/setter or add functions.

Upvotes: 1

praks411
praks411

Reputation: 1992

Since add is the member function of class you can directly access private data members. Normally set and get functions are provided for client access.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258638

You can use either. It depends on whether you want your setters/getters to be just that, or have some additional functionality as well. For example, the getters might also update a counter of how many times that member was accessed, so accessing them through the getter, even inside the class, might make more sense.

Either way, that's not the most important part of the design. You first need to understand what encapsulation really means. Making the members private and providing getters and setters is no better than making them public in the first place (okay, it's a bitter better for debugging purposes, but conceptually it's the same).

Do you really need them?

Also, getters should be made const and you should pass c1 and c2 by const reference.

Upvotes: 5

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6881

Just use it directly. Set/get is to access members from outside the class.

Upvotes: 2

Related Questions