Coders Packet

Create a class with Access Specifiers in C++

By Kinjal Pagar

Today we will learn about how to create a class with Access Specifiers in C++ with the help of an example.

Today we will learn about how to create a class with Access Specifiers in C++.

Access Specifiers (also known as Visibility Specifiers) are the keywords in C++. Which is used to set the scope to the data variables and functions. They used to define whether the data is used to access within the class/ method or outside the class/method.

There are three access specifiers present in C++ as follows

  • PUBLIC   -  Data members accessible outside the class
  • PRIVATE   -  Data members can not be accessible outside the class
  • PROTECTED -  Data members can be accessible in inherited classes.

 

SYNTAX :

Class

{

                           Private :  //declare private variable and function

                           Public :  //declare public variable and function

                           Protected : //declare protected variable and function

}

 

Have a look at the below example, we are going to create a class with the help of these three access specifiers.

 

class Demo

{

    private:  int a;

    protected :    int c;

     public :

        int b;

        void Get_Data();

   

 Demo()

    {

        a = 1;

        b = 2;

        c = 3;

       std::cout<<"Data within constructor : "<<a<<b<<c;

    }       

};




void Demo :: Get_Data()

{

    std::cout<<"\nData within Method : "<<a<<b<<c;

}




int main()

{

    Demo d;

    d.Get_Data();

   

    std::cout<<"\nValue of B within Method : "<<d.b;

   /* std::cout<<"\nData within Method : "<<a<<b<<c;  --> this would not work because variable A and C are declared a Private and Protected */

      return 0;

}

 

Data that may be Private, Public or Protected can be accessed within the class and the method within the class but only the data which is public can be accessed outside the class. As shown in the above example variable a, b and c can be accessed within class and method but only variable B(declared as public) can be accessed in the main method.

 

OUTPUT :

Data within constructor: 123

Data within Method: 123

Value of B within Method: 2

 

 

In this way, we can use Access Specifiers in C++.

 

 

Download project

Reviews Report

Submitted by Kinjal Pagar (kirtypagar)

Download packets of source code on Coders Packet