Explain Access Specifiers in C++
Access specifiers are to the implementation of data hiding, a key idea in Object-Oriented Programming made possible by these Access modifiers. It is additionally called an Access Specifier.
Like variables and methods in other classes, access specifiers in a class determine how accessible its members are.
- In other words, based on the type of Access Specifier will determine whether or not the class members and methods will be directly accessed by the block existent outside the class.
- In a program, we must define variables and methods that other objects of the same class can access and are available throughout the program. Access modifiers assist us in defining that.
In a class, accessibility is assigned to the members using access modifiers or access specifiers, which impose some limitations on the members and prevent direct access to them by external functions.
In C++, there are 3 different categories of access modifiers:
- Public
- Private
- Protected
Recall that the default access modifier for members inside a class is Private if no other access modifiers exist.
A private specifier protects the data from outside members so that it cannot be changed or leaked outside of its block, but a public specifier is used to manipulate and fetch the data.
Let's now look more closely at each of these access modifiers:
Public: All class members listed with the public specifier are accessible to everyone. Other classes and methods may also access the data members and member functions designated as public. A class's public can be accessed from anywhere in the program using the direct member access operator (.) and the object of that class.
Example:
#include<iostream>
using namespace std;
// class definition
class Square
{
Public:
double side;
double compute_area()
{
return side * side;
}
};
// main function
int main()
{
Square obj;
// accessing public data member outside class
obj.side = 4.6;
cout << "Side length is: " << obj.side << "\n";
cout << "Area is: " << obj.compute_area();
return 0;
}
Output:
![Explain Access Specifiers in C++](https://static.tutorialandexample.com/c/explain-access-specifiers-in-cpp1.png)
It creates an object of the Square class named obj using the function. A value of 4.6 is entered into the side variable. After printing the side length, the compute_area() method is then used to calculate and print the square's area.
- Access specifiers regulate the usability of class members by allowing you to specify which members are solely available for internal usage and which can be accessed from outside the class.
Private: Access to class members designated as private is restricted to the member functions of the class. Direct access to any object or method outside the class is not allowed. Only member and friend functions have access to the private information of the class members.
Example:
#include<iostream>
using namespace std;
class Rectangle
{
Private:
double l;
double w;
Public:
double compute_area()
{
return l* w;
}
};
// main function
int main()
{
// creating object of the class
Rectangle obj;
obj.l = 7.5;
obj.w = 4.7;
cout << "Area is: " << obj.compute_area();
return 0;
}
The function produces a Rectangle class object named obj. However, because private members cannot be accessed outside the class, attempting to access length and width from outside the class using the statements obj. length = 7.5; and obj. width = 4.7; will result in a compilation error.
- An error message stating that the private data members are inaccessible will appear in the program's output.
Here is an illustration of a possible error message, because direct access to private members from outside the class is prohibited and is only permitted for internal usage, this error occurs.
Output:
You can create public member functions or methods that can indirectly alter private members and be used to access and edit private members. The provided program's public member function compute_area() accesses the private data member's length and width to determine the rectangle's area. This demonstrates how private members can be used and accessed inside the class.
![Explain Access Specifiers in C++](https://static.tutorialandexample.com/c/explain-access-specifiers-in-cpp2.png)
As mentioned above, the program's output is a compile-time error since we are not allowed to directly access a class's private data members from outside the class. However, because the radius is a private data member and there was a request to access the object area, we got the compilation problem that was previously indicated.
However, indirect access to a class's private data members is possible by utilizing the public member functions of the class.
Example:
#include<iostream>
using namespace std;
class Sphere
{
Private:
double radius;
Public:
void calculate volume(double r)
{
radius = r;
double volume = (4.0/3.0) * 3.14 * r * r* r;
cout << "Radius is: " << r << endl;
cout << "Volume is: " << volume;
}
};
// main function
int main()
{
// creating object of the class
Sphere obj;
obj.calculate volume(2.5);
return 0;
}
Output:
![Explain Access Specifiers in C++](https://static.tutorialandexample.com/c/explain-access-specifiers-in-cpp3.png)
This program shows how to use the C++ private access modifier. It defines a class named Sphere with a public member function called calculateVolume() and a private data member radius.
- The formula (4/3) * pi * r*r is used by the calculated volume () method to determine the volume of a sphere.
- It accepts a parameter r and assigns it to the private data member radius. The console then shows the radius and the estimated volume.
An object of the Sphere class with the name obj is created in the primary () function. This object is given the calculateVolume() function, which receives a radius value 3.5. It is shown that member functions can use and access private data members by accessing and changing the radius within the member function.
Protected: The protected access modifier is similar to private access but modified in that it can only be accessed outside of its class with the aid of a buddy class. The distinction is that any derived class or subclass of that class may also access any members of that class who have been given the Protected designation.
Note: It should be noted that this access through inheritance may alter the access modifier of base class components in derived classes depending on the method of inheritance.
Example
#include<bits/stdc++.h>
using namespace std;
// base class
class Parent
{
// protected data members
protected:
int id_protected;
};
// subclass or derived class from the public base class
class Child: public Parent
{
public:
void setId(int id)
{
id_protected = id;
}
void displayId()
{
cout << "protected are :" << id_protected << endl;
}
};
// main function
int main() {
Child obj1;
// member function of the derived class can
// access the protected data members of the base class
obj1.setId(89);
obj1.displayId();
return 0;
}
Output:
![Explain Access Specifiers in C++](https://static.tutorialandexample.com/c/explain-access-specifiers-in-cpp4.png)
This program serves as an example of the C++-protected access modifier idea. It includes a protected data member named id_protected that defines a base class called Parent. Then it defines the publicly inheriting Child class, which is a derived class from the Parent class. SetId() and displayId() are two member methods of the Child class.
The protected data member id_protected's value is set to the specified value using the setId() function, which accepts an integer id as input. The Child class can access the protected data elements of the base class since it is a descendant of the Parent class. The displayId() function only shows the protected data member id_protected value. In the main() function, an object of the Child class with the name obj1 is created.
Example of Access Specifiers in C++
Consider a business that has various departments that each handle a particular job. Since the HR department has multiple responsibilities, they also oversee the business's finances. Every month, they manage all money matters and credit the employee's account with the salary.
- The wage is one such item that shouldn't be accessible to everyone. The HR division or the employee manager should have access to it to update pay following the appraisal.
- Additionally, the system must be created so that any employee can use their ID to retrieve information about other employees, such as their name, date of hire, etc., but not their pay.
- These access specifiers or access modifiers are utilized. The salary variable can be made private, while the other variables can all be made public.
- We can also create appropriate procedures for updating or obtaining the salary.
Example:
#include <iostream>
using namespace std;
class BaseClass {
public:
int publicVar; // can be accessed from anywhere
void public function() { // can be accessed from anywhere
cout << "This is a public function" << endl;
}
private:
int privateVar; // can only be accessed from the class
void privateFunction() { // can only be accessed from the class
cout << “This is a private function”<< endl;
}
protected:
int protectedVar; // can only be accessed from within the class and its derived classes
void protectedFunction() { // can only be accessed from within the class and its derived classes
cout << "This is a protected function" << endl;
}
};
class DerivedClass: public BaseClass {
public:
void derived function() {
// can access protectedVar and protectedFunction() from base class
cout << "Derived function accessing protectedVar: " << protectedVar << endl;
protectedFunction();
}
};
int main() {
BaseClass obj;
obj.publicVar = 10;
obj.publicFunction();
DerivedClass dObj;
dObj.publicVar = 50;
dObj.publicFunction();
dObj.derived function(); // can access protected member from derived class
return 0;
}
Output:
![Explain Access Specifiers in C++](https://static.tutorialandexample.com/c/explain-access-specifiers-in-cpp5.png)
DerivedClass and BaseClass objects are both created in the primary () function. Both classes' publicVar and public function () can be directly accessed and used. However, directly using the protectedVar, protectedFunction(), privateVar, or privateFunction() will cause compilation issues as they are not available from outside the class.
- The program shows how access specifiers define the visibility and accessibility to enable encapsulation and abstraction.
- It illustrates how private members are only accessible within the class, whereas protected components are accessible within the class and its derived classes.
Advantages and Disadvantages of Access Specifiers in C++
Encapsulation, data hiding, abstraction, support for inheritance, and polymorphism are just a few benefits that access specifiers in C++ offer; they also have restrictions and
- Drawbacks, like restricted access, close coupling, decreased flexibility, and the potential influence of buddy classes and functions. When employing access specifiers, it's crucial to keep a balance to guarantee good encapsulation, maintainability, and code flexibility in your program.
- To make educated choices about the use of access specifiers, consider the requirements and design of your classes and their interactions.
Advantages:
Encapsulation: Access specifiers facilitate encapsulation, a crucial element of oops.
- You can conceal a class's implementation specifics and make only the essential interface visible to the outside world by designating a subset of its members as private.
- This enhances code maintainability and lowers the possibility of unintentional changes being made to internal class data.
Data hiding: The private access specifier enables you to prevent other program components from directly accessing the internal data members of a class.
- Preserving data integrity and prohibiting unauthorized modifications safeguards the class's internal state. Furthermore, data concealing
Abstraction: Access specifiers help define a class's transparent, abstract interface. You can expressly select the functionality made available to class users by designating specific members as public.
- Since they only need to interact with the members available to the public, it is simpler for other developers to comprehend and use the class.
Inheritance and polymorphism: Access specifiers are essential components of inheritance and polymorphism.
- The protected access specifier allows derived classes to access the protected members of the base class.
- Derived classes can use the protected members of the base class without making them visible to the outside world; this encourages code reuse and specialization.
Disadvantages:
Limited Access: Access specifiers limit class members' visibility, which occasionally poses a problem. Granting access to specific program participants from different areas
could be more work.
- Dealing with intricate class dependencies may result in a more complex code structure.
Tight Coupling: Excessive use of public members may cause classes to be tightly coupled. Changes to one class may impact other code areas due to tight coupling.
- The code may become more challenging to maintain and update as changes to a public member may necessitate updates in several locations.
Reduced Flexibility: Access specifiers may make code reuse less flexible. If a member is designated as private, for example, derived classes or other classes cannot access it directly.
- This limitation may constrain the options for expanding or changing a class's behavior, potentially leading to duplicative code or complicated workarounds.
Friend classes and Functions: Access specifiers provide control over member visibility. However, child classes and functions can get around these limitations.
- A class's secret and protected members can be accessed by friend classes and functions, possibly compromising encapsulation and making it harder to understand the code.