Search code examples
c++oopprotected

Why is 'private' used in object oriented program?


There are 'public', 'private', and 'protected' in oop like c++ language. And I tried two kinds of simple programs.

Below is first case in c++.

class A { 

public:
    string name;

}

int main(void) {

    A a;
    a.name;

}

And, second case...

class A { 

protected:
    string name;

public:
    string getName(void) {
        return name;
    }

}

int main(void) {

    A a;
    //a.name;    //can't access
    cout << a.getName();

}

Which one is better in two cases?

Because the information has to be hidden, the second one is maybe better, I think. But in second one, it can also access 'name' variable by using function getName(). If so, although the first one is simpler than second one, why should I use the second one? In other words, why is protected used?


Solution

  • Encapsulation.

    In the first example anyone can use name in any way they wish. In this trivial an example they can't do much harm, but what if name is "Fred" and changing it to "Barney" will crash the program?

    A.name = "Barney";
    

    Program now crashes.

    In the second example, name is inaccessible. getName returns a copy of name. The recipient can do anything they want to this copy without damaging the internal state of A, so

    string temp = A.getName();
    temp = "Barney";
    

    does absolutely nothing.

    Think of this as self defence for objects. Each object now has control over how its internal state is modified and can protect themselves from accidental misuse and damage.

    The users of A don't even have to know how what they get from getName is stored. All they know is they get a string. This decouples A from it's users.