Table of Contents
Back Button
Back to Chapter
C++ Setting Up
C++ Introduction
No items found.
C++ Basics
No items found.
C++ Control Statements
No items found.
C++ Logical Operators
No items found.
C++ Procedural Programming
No items found.
C++ Structural Programming
No items found.
C++ Implementation of OOPS
No items found.
C++ Arrays and Vectors
No items found.
C++ Error Handling
No items found.
C++ File Handling
No items found.

C++ Access Specifiers

C++ access specifiers are used for setting the boundary for the availability of class members (data members and member functions) beyond that class.

There are 3 main access specifiers, private, public and protected .

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/96f4aa2e-59fd-4601-bda7-61c03a2b48f2/Untitled_Diagram_(31).png

Private

Suppose a country possesses some information that it wishes to hide from the outside world, it will classify this information as confidential and hence nobody will have access to this information. While programming there are certain data members or member functions that we wish to keep safe inside a class and prevent direct access to these members from outside the class. This accomplished using the keyword private.

Generally, all data members are usually private because providing direct access to data members is not considered a good practice.

We can not access private members from outside the class.

#include using namespace std; class student { private: int rollno; public: char name[20]; }; main() { student a; cout<<"enter name"; cin>>a.name; cout<
Output: enter name johnny johnny

The code above will only allow us access to the public data member and not to the private member.

Public

This access specifier is like the news we see on television. It is available to everyone and can be used by everyone. Its access is not limited to the class. Now to access private data members we make use of public member functions. The code given below shows us how we can make use of public functions to access private data members.

#include using namespace std; class student { private: int rollno; public: char name[20]; void accessrollno(int rollNo) { rollno=rollNo; } void display() { cout<<"\n Roll no:"<>rollno; a.accessrollno(rollno); cout<<"enter name"; cin>>a.name; cout<
enter roll no.:19 enter name: johnny johnny Roll no:19

Protected

A protected access modifier is similar to a private access modifier in the sense that it can’t be accessed outside of its class unless with the help of a friend class. We will learn more about friend class friend functions in the coming lessons. The protected access modifier is functional only when we are deriving classes using inheritance we will learn more about this in access modifiers 2.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1826a247-22a9-4551-b614-f2488865d3a2/Untitled_Diagram_(32).png

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?