Home »
C++ programming language
Access specifiers (public, protected, private) in C++
C++ provides three access specifiers: public, protected and private
Public Access Specifier
Data members or Member functions which are declared as public can be accessed anywhere in the program (within the same class, or outside of the class).
Protected Access Specifier
Data members or Member functions which are declared as protected can be accessed in the derived class or within the same class.
Private Access Specifier
Data members of Member functions which are declared as private can be accessed within the same class only i.e. the private Data members or Member functions can be accessed within the public member functions of the same class.
Example 1
Consider the following example - demonstrating use of private and public Data members and Member functions
#include <iostream>
using namespace std;
class Example {
private:
int val;
public:
// function declarations
void init_val(int v);
void print_val();
};
// function definitions
void Example::init_val(int v) { val = v; }
void Example::print_val() { cout << "val: " << val << endl; }
int main() {
// create object
Example Ex;
Ex.init_val(100);
Ex.print_val();
return 0;
}
Output
val: 100
In the above example,
Variable val is private and accessing within the public member function init_val() and print_val() Member functions init_val() and print_val() are the public and they accessing within the main function (outside of the class definition) with the help of class’s object Ex
Example 2
Consider the example - demonstrating example of protected
#include <iostream>
using namespace std;
class Example1 {
protected:
int a;
};
class Example2 : public Example1 {
public:
void init_a(int a) { this->a = a; }
void print_a() { cout << "a: " << a << endl; }
};
int main() {
// derived class object
Example2 Ex;
Ex.init_a(100);
Ex.print_a();
return 0;
}
Output
a: 100
In the above example,
Variable a is protected within the class Example1 and the Example1 is base class for Example2 i.e. Example2 is inheriting Example1. Here, variable a can be accessed within the Member functions of Example2