If any class member is declared under private then –
- Such class members can only be accessed by functions declared inside the class
- Not accessible to the outside world(class)
- Only the member functions or the friend functions are allowed to access the private data members of a class.
Example Program –
#include
using namespace std;
class Rectangle{
// this is a private data member
private:
int length, breadth;
// public member function
public:
int area()
{
// Only member function can access private
// this is data member
return length*breadth;
}
};
// main function
int main()
{
// creating object of the class Rectangle
Rectangle rect1;
// This will cause error as we are trying to access private member outside class
rect1.length=10;
rect1.breadth=20;
// trying to access private data member
// directly outside the class
cout << "Area is:" << rect.area();
return 0;
}
output
since length and breadth are private, it will cause error at rect1.length, rect1.breadth, as we are trying to access private members outside the class.
We can solve the issue as follows, as member functions can access the variables inside the class. We create a public function to set values and display them as such –
Example Program –
#include
using namespace std;
class Rectangle
{
//list of private data member
private:
int length, breadth;
// public member function
public:
int area(int l, int b)
{
// since, member function can access private
// data members
length = l;
breadth = b;
int area = length*breadth;
cout << "area is:" << area << endl;
}
};
// main function
int main()
{
// creating object of the class
Rectangle rect1;
// trying to access private data member
// directly outside the class
rect1.area(10,20);
return 0;
}
output