The access modifiers of C++ allows us to determine which class members are accessible to other classes and functions, and which are not.
For example
class Patient {
private:
int patientNumber;
string diagnosis;
public:
void billing() {
// code
}
void makeAppointment() {
// code
}
};
Here, the variables patientNumber and diagnosis of the Patient class are hidden using the private keyword, while the member functions are made accessible using the public keyword.
Types of C++ Access Modifiers
In C++, there are 3 access modifiers:
- public
- private
- protected
public Access Modifier
- The public keyword is used to create public members (data and functions).
- The public members are accessible from any part of the program.
#include <iostream>
using namespace std;
// define a class
class Person {
// public elements
public:
int age;
void displayAge() {
cout << "Age = " << age << endl;
}
};
int main() {
// declare a class object
Person obj1;
cout << "Enter your age: ";
// store input in age of the obj1 object
cin >> obj1.age;
// call class function
obj1.displayAge();
return 0;
}
In this program, we have created a class named Person, which contains a public variable
age and a public function displayAge().
In main(), we have created an object of the Person class named obj1. We then access the
public elements directly by using the codes obj1.age and obj1.displayAge().
Note
The public elements are accessible from main(). This is because public elements are
accessible from all parts of the program.
private Access Modifier
- The public keyword is used to create private members (data and functions).
- The public members can only be accessed from within the class.
- However, friend classes and friend functions can access private member
#include <iostream>
using namespace std;
// define a class
class Person {
// private elements
private:
int age;
// public elements
public:
void displayAge(int a) {
age=a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare a class object
Person obj1;
cout << "Enter your age: ";
cin>>ageInput;
// call function and pass ageInput as argument
obj1.displayAge(ageInput);
return 0;
}
Output
In main(), the object obj1 cannot directly access the class variable age.
// error
cin >> obj1.age;
We can only indirectly manipulate age through the public function displayAge(),
since this function initializes age with the value of the argument passed to it i.e.
the function parameter int a.
protected Access Modifier
Before we learn about the protected access specifier, make sure we know about
inheritance in C++.
The protected keyword is used to create protected members (data and function).
The protected members can be accessed within the class and from the derived class.
Note:
By default, class members in C++ are private, unless specified otherwise.
No comments:
Post a Comment