0% found this document useful (0 votes)
11 views2 pages

Access Specifier

The document explains C++ access specifiers, which determine how class members can be accessed. There are three access specifiers: public (accessible from outside), private (not accessible from outside), and protected (accessible in inherited classes). An example illustrates the differences between public and private members, highlighting access rules and potential errors when accessing private members.

Uploaded by

sushmoykar612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Access Specifier

The document explains C++ access specifiers, which determine how class members can be accessed. There are three access specifiers: public (accessible from outside), private (not accessible from outside), and protected (accessible in inherited classes). An example illustrates the differences between public and private members, highlighting access rules and potential errors when accessing private members.

Uploaded by

sushmoykar612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Access Specifiers

Private
Protected
public
❮ PreviousNext ❯

Access Specifiers

By now, you are quite familiar with the public keyword that
appears in all of our class examples:

Example
class MyClass { // The class
private: int roll; // Access specifier
// class members goes here
};

Try it Yourself »

The public keyword is an access specifier. Access specifiers


define how the members (attributes and methods) of a class can
be accessed. In the example above, the members are public -
which means that they can be accessed and modified from
outside the code.

However, what if we want members to be private and hidden from


the outside world?

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.
You will learn more about Inheritance later.
In the following example, we demonstrate the differences
between public and private members:

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

class child : Myclass {

}
int main() {
clild myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
myObj.z=100; // Allowed (protected)
return 0;
}

If you try to access a private member, an error occurs:


error: y is private
Try it Yourself »

You might also like