Access Specifiers in C++
Declaration of class:
class CLASS_NAME
{
//Access Specifier
Data Members
Member Functions
};
Data members are data type properties that describe the characteristics of a class. There may be zero or more data members of any type in a class.
Member functions are the set of operations that may be applied to the objects of that class. It is the interface between the class members and object. It is always single it doesn’t make any copy. There may be zero or more member functions in a class.
Program Access Level that control access to members from within the program. These access levels are private, protected or public. Depending upon the access level of a class member , access to it is allowed or denied.
Class name that serves as a type specifier for the class using which object of this class type can be created.
For Example
#include <iostream.h>
class sum // class
{
int a,b,s; //data members
public:
sum() // constructor
{
a=10;
b=20;
}
void show() //member function
{
s=a+b;
cout<<”sum of numbers is”<<s<<endl;
}
};
int main()
{
sum obj; //object of class
obj.show();
return 0;
}
public, protected and private are three access specifiers in C++.
IF YOU DON’T SPECIFY ANY ACCESS SPECIFIER WITH A DATA MEMBER OR WITH A MEMBER FUNCTION, THE ACCESS SPECIFIER FOR THOSE MEMBERS WILL BE TREATED AS private BY DEFAULT.
The general form of class definition is given below.
class class-name{
private:
Data Members/Member Functions
protected:
Data Members/Member Functions
public:
Data Members/Member Functions
};
The class body contains the declaration of members (data and functions). There are generally three types of member in a class: private, protected and public which are grouped under three sections namely private: protected: and public:.
The private member can be accessed only from within the class and public members can be accessed from outside the class also. If no access specifier (public, protected or private) is specified then by default, members are private.
Private variables can only be accessed by the class
Class A
{
private:
int x;
public:
void SetX(int n) { x = n; } //this is ok
};
int main()
{
A aobj;
aobj.x = 0; //error because x is private and not accessible outside the class
}
Protected is similar to private but can also be accessed by inherited classes
class A
{
protected:
int x;
public:
void SetX(int n) { x = n; } // this is ok
};
class B : public A
{
public:
void ShowX() { cout << x << “n”; }
// this is ok as x is protected member
};
Public member can be accessed from outside the class
class A
{
public:
int x
void SetX(int n) { x = n; } // <<< this is ok
};
int main()
{
A aobj;
aobj.x = 0;
// Ok because x is public accessible outside the class
}
}