c Access Specifier
c Access Specifier
com
Access Specifier
(Public, Private and Protected)
Now before studying how to define class and its objects, let’s first quickly learn what
access are specifier. Access specifier in C++ class defines the access control rules.
C++ has 3 new keywords introduced, namely,
1. public
2. private
3. protected
Syntax:
class base
{
.... ... ....
};
ASHISH PRAJAPATI 1
www.ashishprajapati29.wordpress.com
These access specifiers are used to set boundaries for availability of members of
class be it data members or member functions. Access specifiers in the program, are
followed by a colon. You can use either one, two or all 3 specifiers in the same class
to set different boundaries for different class members. They change the boundary
for all the declarations that follow them.
PUBLIC:
Public, means all the class members declared under public will be available to
everyone. The data members and member functions declared public can be accessed
by other classes too. Hence there are chances that they might change them. So the
key members must not be declared public. A public member is accessible from
ASHISH PRAJAPATI 2
www.ashishprajapati29.wordpress.com
anywhere outside the class but within a program. You can set and get the value of
public variables without any member function.
Syntax:
PRIVATE:
Private keyword, means that no one can access the class members declared private
outside that class. If someone tries to access the private member, they will get a
compile time error. By default class variables and member functions are private.
Syntax:
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
A private member variable or function cannot be accessed, or even viewed from o
utside the class. Only the class and friend functions can access private members.
By default all the members of a class would be private, for example in the followin
g class width is a private member, which means until you label a member, and it w
ill be assumed a private member:
ASHISH PRAJAPATI 3
www.ashishprajapati29.wordpress.com
class Box
{
double width;
public:
double length;
void setWidth ( double wid );
double getWidth ( void );
};
PROTECTED:
Protected, is the last access specifier, and it is similar to private, it makes class
member inaccessible outside the class. But they can be accessed by any subclass of
that class. (If class A is inherited by class B, then class B is subclass of class A. We
will learn this later.)
Syntax:
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
ASHISH PRAJAPATI 4
www.ashishprajapati29.wordpress.com
ASHISH PRAJAPATI 5