48

I don't understand the difference between protected and private members or methods, as I assumed both will hide the member or the function to access from outside the class.

What is the difference between the protected and the private keywords?

0

5 Answers 5

88

private - only available to be accessed within the class that defines them.

protected - accessible in the class that defines them and in other classes which inherit from that class.

16

Things that are private are only visible within the class itself.

Things that are protected are visible in the class itself and in subclasses.

9

The difference is who can access those functions.

  • Private = only members of the same class can access the function.

  • Protected = Same as private but derived classes can also access.

6

Private members can only be used by that classes members and its friends; protected members can be inherited by other classes, and can be used by the classes members and friends.

5

Private methods are usually visible to class instances (internal implementations), protected methods are visible to subclasses and classes in the same package (inheritance and restricted usage).

Not the answer you're looking for? Browse other questions tagged or ask your own question.