Articles

What are access specifiers in C++?

What are access specifiers in C++?


In this chapter of C++ interview questions, we will learn about:

  • what are access specifiers in c++
  • types of access specifiers in c++
  • examples of access specifiers in c++

Use of access specifiers in C++

Data Hiding is an important aspect of Object-Oriented Programming.

 

In C++ access specifiers are used to facilitate this feature. Access specifiers are used to provide certain level of permission to access data in class members.

 

Types of Access Specifiers

i) Private: Private members of a class are accessible only from within other members of the same class or from 'friends'.

 

ii) Protected: It is some similarity with a private access specifier. The difference it can be accessed from a derived class or friend class/ child class.

 

iii) Public: Public members are accessible from anywhere, it is accessed through access operator(.) with the object of the class.


Examples of access specifiers in c++(Public & Private)

class TIH {
  public:  // Public access specifier
    int a;  
  private:  // Private access specifier
    int b; 
};

int main() {
  TIH obj; //Object created
  obj.a = 22;  // Allowed (public) accessed through (.) opeartor
  obj.b = 43;  // Not allowed (private)
  return 0;
}

Output

error obj.b=43 // Not allowed


Examples of access specifiers in c++ (Protected)

#include <iostream>
using namespace std;
 
class A {
   protected:
      int x;
};
 
class B:A { // B is the derived class.
   public:
      void setting( int x1 );
      int getting( void );
};
 
// Member functions of child class
int B::getting(void) {
   return x ;
}
 
void B::setting( int x1) {
   x = x1;
}
 

int main() {
   B b1;
 
   
   b1.setting(10);
   cout << "Value is : "<< b1.getting() << endl;
 
   return 0;
}

Output

Value is : 10


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Jan 19,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!