C++ Access Specifiers C-PLUS-PLUS

C++ Access Specifiers  

C++ Access Specifiers

C++ Access Specifiers

In C++, there are three access specifiers:

  • public - members are accessible from outside the class
  • private - members cannot be accessed (or viewed) from outside the class
  • protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.


#include <iostream>
using namespace std;

class MyClass {
  public:     // Public access specifier
    int x;      // Public attribute
  private:    // Private access specifier
    int y;      // Private attribute

int main() {
  MyClass myObj;
  myObj.x = 21;  // Allowed (x is public)
  myObj.y = 40;  // Not allowed (y is private)
  return 0;


In function 'int main()':
Line 8: error: 'int MyClass::y' is private
Line 14: error: within this context

Download free E-book of C-PLUS-PLUS

Learn Programming for Free

Join Programmers Community on Telegram

Talk with Experienced Programmers

Just drop a message, we will solve your queries