Access Specifier
Imagine that you are writing a payroll processing program. Do you think it would be a good idea to let anyone see the pay rate for an employee? What about other parts of the program? It would make the most sense to keep a data element safe within its own function, and not make it available to just anyone?
In object-oriented programming, one of the major features is the idea of encapsulation or data hiding. This means you can keep certain things away from other functions or routines. There are 3 types of specifiers:
| Specifier | Description |
|---|---|
| Public | Available anywhere in the program. |
| Private | Cannot be seen or accessed outside the class. |
| Protected | Similar to private, but can be accessed by child classes of the current class. |
Let's take a look at each of these and how you can use them. We will be using a class called Employee. Recall our payroll example: There are some elements about an employee that are public and others that we want to keep safe.
Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −
| Access | public | protected | private |
|---|---|---|---|
| Same class | yes | yes | yes |
| Derived classes | yes | yes | no |
| Outside classes | yes | no | no |
A derived class inherits all base class methods with the following exceptions −
- Constructors, destructors and copy constructors of the base class.
- Overloaded operators of the base class.
- The friend functions of the base class.
We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied −
- Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's privatemembers are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
- Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
- Private Inheritance − When deriving from a private base class, public and protected members of the base class become privatemembers of the derived class.
Comments
Post a Comment