C++ Class Access Specifiers

Introduction

The class access specifiers could disable access to member fields but allow access to member functions for our object and other entities accessing our class members.

They specify access for class members.

There are three access specifiers/labels: public, protected, and private:

class MyClass /*  ww w. ja v a2s  .  com*/
{ 
public: 
    // everything in here 
    // has public access level 
protected: 
    // everything in here 
    // has protected access level 
private: 
    // everything in here 
    // has private access level 
}; 

Default visibility/access specifier for a class is private if none of the access specifiers is present:

class MyClass 
{ 
    // everything in here 
    // has private access by default 
}; 

Another way to write a class is to write a struct.

A struct is also a class in which members have public access by default.

So, a struct is the same thing as a class but with a public access specifier by default:

struct MyStruct 
{ 
    // everything in here 
    // is public by default 
}; 

For now, we will focus only on public and private access specifiers.




PreviousNext

Related