C++ Access Modifiers
C++ Access Modifiers
Raj Kumar
C++ Access Modifiers
One of the main features of object-oriented
programming languages such as C++ is data hiding.
Data hiding refers to restricting access to data members
of a class. This is to prevent other functions and classes
from tampering with the class data.
However, it is also important to make some member
functions and member data accessible so that the
hidden data can be manipulated indirectly.
The access modifiers of C++ allows us to determine
which class members are accessible to other classes and
functions, and which are not.
Types of C++ Access Modifiers
1.Public
2.Private
3.Protected
Public, Private, and Protected
1. Public elements can be accessed by all other
classes and functions.
2. Private elements cannot be accessed outside
the class in which they are declared, except
by friend classes and functions.
3. Protected elements are just like the private,
except they can be accessed by derived
classes.
Public, Private, and Protected
Same Derived Outside
Specifiers
class class class
Private Yes No No
// define a class
class Sample {
// public elements
public:
int age;
void displayAge() {
cout << "Age = " << age << endl;
}
};
void main() {
// private elements
private:
int age;
// public elements
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
Void main() {
int ageInput;
// declare an object
Sample obj1;
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
void main() {
int ageInput;