This is an old revision of the document!
Visibility is a major feature of Object-Oriented Programming (OOP) allowing architects and engineers to design rules covering the visibility of an Object's state variables and operations to other objects within the application or system.
for instance to prevent a certain variable to be modified from outside the class. The default visibility is public, which means that the class members can be accessed from anywhere. This means that declaring the visibility is optional, since it will just fall back to public if there is no access modifier. For backwards compatibility, the old way of declaring a class variable, where you would prefix the variable name with the “var” keyword (this is from PHP 4 and should not be used anymore) will also default to public visibility.
visibility of a class member variable or member function determines from where that variable can be accessed/modified, or from where the member function can be called.
| Visibility | Description |
|---|---|
| public | The member variable/function can be accessed/called in any statement within any function. |
| protected | The member variable/function can only be accessed/called in the statements of functions of the class to which the variables/functions belong and any derived classes (subclasses). |
| private | The member variable/function can only be accessed/called in the statements of member functions of the class to which the variables/functions belong. |
<Code cpp linenums:1 | An example of using Visibility labels in a simple C++ program1).> C++ implementation to show Visibility modes
#include <bits/stdc++.h> using namespace std;
class BaseClass { ===== Public public: int x; ===== Protected
protected:
int y;
//===== Private
private:
int z;
}; End BaseClass DerivedClass inherits from BaseClass class DerivedClass : public BaseClass { }; End DerivedClass main function int main() {
DerivedClass derivedClass; // x is labeled public, therefore it's value is displayed in the standard output stream cout << derivedClass.x << endl; // y is labeled protected, therefore the compiler displays a visibility error cout << derivedClass.y << endl; // z is labeled private within BaseClass, therefore the compiler displays a visibility error cout << derivedClass.z << endl;
}; End main </Code> : Note: Often the coding styles specify the attributes with a particular label be listed together (i.e., all public state variables listed together, etc.) and they are listed alphabetically within the group. The Labels are listed from least restrictive to most restrictive (i.e., public, protected, and private) ~~DISCUSSION:on|Outstanding Issues~~ ~~DISCUSSION:off~~