CPP Class Access Modifiers12456
CPP Class Access Modifiers12456
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.
The access restriction to the class members is specified by the labeled public, private, and
protected sections within the class body. The keywords public, private, and protected are called
access specifiers.
A class can have multiple public, protected, or private labeled sections. Each section remains in
effect until either another section label or the closing right brace of the class body is seen. The
default access for members and classes is private.
class Base {
public:
protected:
private:
};
#include <iostream>
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
When the above code is compiled and executed, it produces the following result:
Length of line : 6
Length of line : 10
By default all the members of a class would be private, for example in the following class width is
a private member, which means until you label a member, it will be assumed a private member:
class Box
{
double width;
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
You will learn derived classes and inheritance in next chapter. For now you can check following
example where I have derived one child class SmallBox from a parent class Box.
Following example is similar to above example and here width member will be accessible by any
member function of its derived class SmallBox.
#include <iostream>
using namespace std;
class Box
{
protected:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 5