Access Specifiers |
The class declaration looks very much like Figure Below with the addition of two key words, private and public. These are called access specifiers, because they designate who can access various members of the class. Notice that each access specifier is followed by a colon. A public member variable can be accessed by functions outside the class and a public member function can be called by functions outside the class. A private member variable, on the other hand, can only be accessed by a function that is a member of the same class and a private member function can only be called by other functions that are members of the class. If we had omitted the words public and private altogether, everything would have defaulted to being private. This would not have been very useful because then, except in special circumstances, no functions outside the class could ever use the class.
In our Circle class, the member variable radius is declared to be private and the member functions are declared to be public. This is common. Member data is usually made private to safeguard it. Public functions are then created to allow carefully controlled access to this data from outside the class. For now, all our class member variables will be declared as private and all our member functions will be declared as public. Later you will see cases where private member functions are used.
NOTE:
If a program statement outside a class attempts to access a private member, a compiler error will result. Later you will learn how outside functions may be given special permission to access private class members.
Placement of private and public Members
It does not matter whether we list the private or public members first. In fact, it is not even required that all members of the same access specification be declared together. Both examples below are legal declarations of the Circle class.
However, most programmers consider it more orderly and preferable to separate private and public members.
2 comments
Click here for commentsgood job (kohistani)
ReplyThank you very much for your reviews .
ReplyConversionConversion EmoticonEmoticon