Session 11
Session 11
PROGRAMMING
ACCESS SPECIFIERS
Access control in classes
•public : A public member is accessible from anywhere outside the class but within a program.
•private : A private member variable or function cannot be accessed, or even viewed from
outside the class. Only the class and friend functions can access private members.
•protected
• : A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are called derived
classes
2
Example 1: C++ public Access Specifier
6
Example 2: C++ private Access Specifier
#include <iostream>
using namespace std; int main()
class Sample
{ {
private: // private elements int ageInput;
int age; Sample obj1;
cin >> obj1.age; // displays error
public: // public elements cout << "Enter your age: ";
void displayAge(int a)
cin >> ageInput;
{
age = a; obj1.displayAge(ageInput);
•
cout << "Age = " << age << endl; return 0;
} }
};
OUTPUT
10
Revision Exercises
•Even though the prototypes for friend functions appear in the class definition, friends are not member
functions.
•A friend can be a function, function template, or member function, or a class or class template, in
which case the entire class and all of its members are friends.
12
Friend function
• In C++, a friend function is a function that is declared using the friend keyword to achieve the
encapsulation feature and can access the private and protected data members easily by using
functions.
• To access the data in C++, friend functions are declared inside the body of the class or inside the
13
Friend function Example
• When the inline function is called whole code of the inline function gets inserted or substituted
at the point of inline function call. This substitution is performed by the C++ compiler at compile
time.