close
The Wayback Machine - https://web.archive.org/web/20240826020730/https://www.geeksforgeeks.org/access-modifiers-in-c/
Open In App

Access Modifiers in C++

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding. Consider a real-life example: 
The Research and Analysis Wing (R&AW), having 10 core members, has come into possession of sensitive confidential information regarding national security. Now we can correlate these core members to data members or member functions of a class, which in turn can be correlated to the R&A Wing. These 10 members can directly access the confidential information from their wing (the class), but anyone apart from these 10 members can’t access this information directly, i.e., outside functions other than those prevalent in the class itself can’t access the information (that is not entitled to them) without having either assigned privileges (such as those possessed by a friend class or an inherited class, as will be seen in this article ahead) or access to one of these 10 members who is allowed direct access to the confidential information (similar to how private members of a class can be accessed in the outside world through public member functions of the class that have direct access to private members). This is what data hiding is in practice. 
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members, i.e., they set some restrictions on the class members so that they can’t be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++: 

  1. Public
  2. Private
  3. Protected

Note: If we do not specify any access modifiers for the members inside the class, then by default the access modifier for the members will be Private.

Let us now look at each one of these access modifiers in detail:
 1. Public: All the class members declared under the public specifier will be available to everyone. The data members and member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class. 

Example: 

CPP




// C++ program to demonstrate public
// access modifier
  
#include<iostream>
using namespace std;
  
// class definition
class Circle
{
    public: 
        double radius;
          
        double  compute_area()
        {
            return 3.14*radius*radius;
        }
      
};
  
// main function
int main()
{
    Circle obj;
      
    // accessing public datamember outside class
    obj.radius = 5.5;
      
    cout << "Radius is: " << obj.radius << "\n";
    cout << "Area is: " << obj.compute_area();
    return 0;
}


Output: 

Radius is: 5.5
Area is: 94.985

In the above program, the data member radius is declared as public so it could be accessed outside the class and thus was allowed access from inside main(). 
 2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class. 

Example: 

CPP




// C++ program to demonstrate private
// access modifier
  
#include<iostream>
using namespace std;
  
class Circle
{   
    // private data member
    private: 
        double radius;
       
    // public member function    
    public:    
        double  compute_area()
        {   // member function can access private 
            // data member radius
            return 3.14*radius*radius;
        }
      
};
  
// main function
int main()
{   
    // creating object of the class
    Circle obj;
      
    // trying to access private data member
    // directly outside the class
    obj.radius = 1.5;
      
    cout << "Area is:" << obj.compute_area();
    return 0;
}


Output: 

 In function 'int main()':
11:16: error: 'double Circle::radius' is private
         double radius;
                ^
31:9: error: within this context
     obj.radius = 1.5;
         ^

The output of the above program is a compile time error because we are not allowed to access the private data members of a class directly from outside the class. Yet an access to obj.radius is attempted, but radius being a private data member, we obtained the above compilation error. 

However, we can access the private data members of a class indirectly using the public member functions of the class. 

Example: 

CPP




// C++ program to demonstrate private
// access modifier
  
#include<iostream>
using namespace std;
  
class Circle
{   
    // private data member
    private: 
        double radius;
       
    // public member function    
    public:    
        void compute_area(double r)
        {   // member function can access private 
            // data member radius
            radius = r;
              
            double area = 3.14*radius*radius;
              
            cout << "Radius is: " << radius << endl;
            cout << "Area is: " << area;
        }
      
};
  
// main function
int main()
{   
    // creating object of the class
    Circle obj;
      
    // trying to access private data member
    // directly outside the class
    obj.compute_area(1.5);
      
      
    return 0;
}


Output: 

Radius is: 1.5
Area is: 7.065

3. Protected: The protected access modifier is similar to the private access modifier in the sense that it can’t be accessed outside of its class unless with the help of a friend class. The difference is that the class members declared as Protected can be accessed by any subclass (derived class) of that class as well. 

Note: This access through inheritance can alter the access modifier of the elements of base class in derived class depending on the mode of Inheritance.

Example: 

CPP




// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;
  
// base class
class Parent
{   
    // protected data members
    protected:
    int id_protected;
     
};
  
// sub class or derived class from public base class
class Child : public Parent
{
    public:
    void setId(int id)
    {
          
        // Child class is able to access the inherited 
        // protected data members of base class
          
        id_protected = id;
          
    }
      
    void displayId()
    {
        cout << "id_protected is: " << id_protected << endl;
    }
};
  
// main function
int main() {
      
    Child obj1;
      
    // member function of the derived class can
    // access the protected data members of the base class
      
    obj1.setId(81);
    obj1.displayId();
    return 0;
}


Output: 

id_protected is: 81


Previous Article
Next Article

Similar Reads

Interesting facts about data-types and modifiers in C/C++
Here are some logical and interesting facts about data-types and the modifiers associated with data-types:- 1. If no data type is given to a variable, the compiler automatically converts it to int data type. C/C++ Code #include &lt;iostream&gt; using namespace std; int main() { signed a; signed b; // size of a and b is equal to the size of int cout
4 min read
Modifiers for Vector in C++ STL
Click here for Set 1 of Vectors. Modifiers 1.1 assign(input_iterator first, input_iterator last) - Assigns new content to vector and resize 1.2 assign(size_type n, const value_type g) - Assigns new content to vector and resize #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { vector &lt;int&gt; g1; vector &lt;int
5 min read
C++ Type Modifiers
Modifiers are used in C++ to change or give extra meaning to already existing data types. It's added to primitive data types as a prefix to change their meaning. A modifier is used to change the meaning of a basic type so that it better matches the requirements of different circumstances. Following are the C++ data type modifiers: signedunsignedsho
6 min read
"Access is Denied error" in C++ Visual Studio and How to resolve it
Pre-requisite: How to Install Visual C++ on Windows In this article, we will discuss about access denied error in Visual Studio in C++. What is Access denied error in Visual Studio in C++? Access denied error in Visual Studio in C++ occurs when there is an attempt to access one of the installation files and due to some reason the access is denied t
3 min read
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()substr()find()find_first_of()find_last_of() Let's start
4 min read
How to Access Elements in Set by Index in C++?
Sets are the containers that are available in the C++ Standard Template Library (STL). They are used to hold distinct elements in a predetermined sequence; fundamentally, it operates on the same principles as a binary search tree. In C++, elements can be added to or removed from sets, but they cannot be modified after being stored there since their
4 min read
How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?
Local Variable: The variable whose scope lies inside a function or a block in which they are declared. Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolutio
2 min read
What happens when more restrictive access is given to a derived class method in C++?
We have discussed a similar topic in Java here. Unlike Java, C++ allows to give more restrictive access to derived class methods. For example the following program compiles fine. C/C++ Code #include&lt;iostream&gt; using namespace std; class Base { public: virtual int fun(int i) { } }; class Derived: public Base { private: int fun(int x) { } }; int
2 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Random Access Iterators in C++
After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?Random-access iterators are one of the five main types of iterators present in C++ Standard Library, others
6 min read
C++ Inheritance Access
Prerequisites: Class-Object in C++Inheritance in C++Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are: public - members are accessible from outside the class, and members can be accessed from anywhere.private - members cannot be accessed (or viewed) from outside the
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :