Answers: Access specifier in C++ is to control the access of data and member functions of a class. We may want some data members or functions not to be visible out side of the class or to main program or to another class etc. So, we use access specifiers in C++.
C++ supports three type of access specifiers that is public, private and protected access specifiers.
Default access specifier in C++ is private access specifier. Means, if we don’t put any access specifier in a class before data and functions, all data and functions will be private.
For example, in below class all the data members and functions are private.
class Car{
int carID;
void run(){
}
void engine(){
}
};
Class containing all type of access specifiers in C++ – example
class Car{
// By default : Private. all data and
//functions under this section will be
//by default private.
//only use in this class itself
int carID;
void engine()//private by default
{
}
public:
//public : Any user can access ie another classes
//main() program etc.
void getCarInfo(){
}
protected:
//protected : only child class can access
void CarFunction(){}
private:
//private : only this class can access
void wheelType()//private by default
{
}
};
Private access specifier: –Data and functions can’t be accessed outside of a class.
Protected access specifier: Data and functions are only accessible to child class in an inheritance.
Public access specifier: Data and functions are accessible from everywhere outside of a class.
I have answer here the use of access specifiers in C++ with detail that also describes, what issue is, if we use public specifier instead of private.