C++ Access Specifier
C++ Access Specifier
Data hiding is one of the important features of Object Oriented Programming which
allows preventing the functions of a program to access directly the internal
representation of a class type.
C++ access specifiers are used for determining or setting the boundary for the availability of
class members (data members and member functions) beyond that class.
For example, the class members are grouped into sections, private protected and public. These
keywords are called access specifiers which define the accessibility or visibility level of class
members.
The keywords public, private, and protected are called access specifiers.
protected:
// protected members go here
public:
// public members go here
};
class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Length of line : 6
Length of line : 10
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so
that they can be called from outside of the class as shown in the following program.
#include <iostream>
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Length of box : 10
Width of box : 10
class Box {
protected:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Width of box : 5