Access Specifiers in C++

In this tutorial, we will learn about the access specifiers through  C++.
Why we use access specifiers and what are the types in the access specifiers.

Access specifiers

Access specifiers, in other words, called access modifiers are used to implement important features of the object-oriented programming known as the Data Hiding.
They are used in in a  class are used to set accessibility of the class members. However, it sets some restrictions on the class members not to get directly accessed outside the class.

Types of Access specifiers:

There are 3 types of access specifiers available in c++:


  1. Public
  2. Private
  3. Protected

Access specifiers are followed by a colon.


  • Public means all the class members declared under the public will be available to everyone.
  • Hence there is a chance that the outside other class might change them.
  • So key members must not be declared public.
  • written as public:


  • It means that no one can access the class members declared private outside that class.
  • By default, the class members are private.
  • written as private:


  • It is similar to private , but protected class members can be accessed by any subclass i.e , derived class of that class.
    (If class A inherited by class B, then class B is subclass of class A)
  • written as private:

Simple class example

class item
char name[15];
int number;
float cost;
void getdata();
void putdata();

Scope Resolution operator:

Scope resolution operator in c++ has two applications.

  1. For differentiating global and local variable when both have the same name.
  2. To identify the class a member function is belonging to.

Scope resolution operator is denoted by ::

Program to differentiate global and local variable using scope resolution operator.

using namespace std;
int a=10; // global variable
int main()
{int a=20; // local variable
cout<<"Local variable a = "<<a;
cout<<"Global variable a = "<<::a;


Local variable a =20
Global variable a=10
  • A  major application of the scope resolution operator is in classes.
  • Similarly To define a class member function outside the class definition we use scope resolution operator as follows:
return_type class_name :: function_name(parameter_list)
   // function body

Program  to demonstrate the use of the scope resolution operator to define member function outside the class

using namespace std;
class demo
int n;
void getdata();
void display();
void demo::getdata()
cout<<"\n Enter an integer: ";
void demo::display()
cout<<"\n n= "<<n;
int main()
demo d1,d2;
cout<<"\n For object d1";
cout<<"\n For object d2";


Enter an integer:7
Enter an integer:24
For object d1
For object d2

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *