The Private keyword

This post is about a very crucial element of Object Oriented Programming known as Data Hiding. This is implemented using Access Modifiers in C++. There are three types of access modifiers namely,private,public and protected. Today we are going to talk about the private access modifiers.

Why do we need access modifiers?

A crucial element of programming is data hiding. We don’t want every variable to be accessible from outside the class. This is a sort of encapsulation where the members are accessed according to the modifiers we set. Consider the starting of an engine,we want the user only to press the switch so that the engine starts,we don’t want the user to fiddle with the intricacies of the working of the engine. We press the switch and boom the engine starts. On the other hand if we let the user modify the working of the engine then that may blow up the car, isn’t it? Ok, that wasn’t the best of examples but you get it right? So enters the scene is what is known as the private access modifier. Let’s look at a bit of code and what it does…

The Private Access Modifier

using namespace std;
class Square
    // private data member
        double side;
    // public member function   
        double  calc_area()
        {   // member function can access private
            // data member side
            return side*side;
// main function
int main()
    // creating object of the class
    Square obj;
    // trying to access private data member
    // directly outside the class
    obj.side = 6;
    cout << "Area of square is " << obj.calc_area();
    return 0;

In the above code note how we have declared the side as private inside the class Square. Since it is private it can only be accessed from functions within the class or a friend function . In the above example as we are trying to access it inside main using obj.side the compiler will throw an error in this case as the private ‘side’ variable is not visible from the main function. This is how we hide crucial data that is not meant to be accessed from outside the class.

Hope this has been helpful, Cheers.

Related :

Follow :