0 votes
in C Plus Plus by

What are the various Access Specifiers in C++?

1 Answer

0 votes
by
C++ supports the following access specifiers:

Public: Data members and functions are accessible outside the class.

Private: Data members and functions are not accessible outside the class. The exception is the usage of a friend class.

Protected: Data members and functions are accessible only to the derived classes.

Example:

Describe PRIVATE, PROTECTED and PUBLIC along with their differences and give examples.

class A{

             int x; int y;

             public int a;

             protected bool flag;

             public A() : x(0) , y(0) {} //default (no argument) constructor

 };

 

 main(){

  

A MyObj;

  

MyObj.x = 5; // Compiler will issue a ERROR as x is private

  

int x = MyObj.x; // Compiler will issue a compile ERROR MyObj.x is private

  

 MyObj.a = 10; // no problem; a is public member

 int col = MyObj.a; // no problem

  

 MyObj.flag = true; // Compiler will issue a ERROR; protected values are read only

 bool isFlag = MyObj.flag; // no problem

Related questions

+1 vote
+2 votes
+1 vote
asked Jan 20, 2021 in C Plus Plus by SakshiSharma
0 votes
asked Jun 15, 2020 in C Plus Plus by Robindeniel
...