In this tutorial, you will learn about c++ access modifiers, how to use access specifiers in c++ with clear program examples.
ACCESS MODIFIERS
- It is mainly used to decide the scope of various programming elements such as variables, functions, constructor, destructor, etc, ..
- It gives the scope and life time to object properties (instance variables & functions) and class properties (static variables & functions)
- It is used to access the state (e.g. variable) and behavior (e.g function) of objects / class
- It is used to set the access privilege levels to members of a class (e.g. variables/functions)
- C++ supports three different types of modifiers. They are:
- Private (Default for variables / functions / constructors)
- Public
- Protected.
Usage
- It is used to implement the important feature of oops called as data hiding.
Access Levels
GENERAL SYNTAX OF ACCESS MODIFIER
class <name>
{
private:
// private members (variables & functions)
public:
// public members (variables & functions)
protected:
// protected members (variables & functions)
};
Example
class Test
{
private:
int number;
char address[100];
protected:
char name[100];
public:
void disp() { … }
};
1. PRIVATE MODIFIER
- It is accessible only within a same class (current class)
- Private data can’t accessible in outside of a class or main function
- It is the default modifier of class members such as variables / functions / constructors / destructors, etc, …
- It gives more security than other modifiers
Usage
- It is used to implement the concept of data hiding (information hiding) feature.
NOTE
- All the members and function of a class is private by default. (If no access modifier is specified).
1. EXAMPLE OF PRIVATE MODIFIER