|
Page 4 of 6 Public, Protected and Private Labels C++ supports three labels that can be used in classes (or structs) to define the permissions for the members in that section of the class. These labels can be used multiple times in a class declaration for cases where it's logical to have multiple groups of these types. These keywords affect the permissions of the members -- whether functions or variables. public This label is used to say that the methods and variables may be accessed from any portion of the code that knows the class type. This should usually only be used for member functions (and not variables) and should not expose implementation details. protected Only subclasses of this type may access these functions or variables. Many people prefer to also keep this restricted to functions (as opposed to variables) and to use accessor methods for getting to the underlying data. private This is used for methods that can not be used in either subclasses or other places. This is usually the domain of member variable and helper functions. It's often useful to start off by putting functions here and to only move them to the higher levels of access as they are needed. Note: It's often misunderstood that different instances of the same class may access each others' private or protected variables. A common case for this is in copy constructors. class Foo { public: Foo( const Foo &f ) { m_value = f.m_value; // perfectly legal }
private: int m_value; } (It should however be mentioned that the above is not needed as the default copy constructor will do the same thing.)
|