Through getter setter methods we can indirectly access private data members of the class
as shown in the below code. Then what is the significance of encapsulation in OOPS concept. I am not getting the appropiate answer for that. Can anyone help me?
Thanks in advance

using namespace std;
class Test
        int a;
        int b;
        void setValue(int val)
        int getValue()
                return a;
int main()
        Test objTest;
        int result=objTest.getValue();
        return 1;

The differences I think are in that, with data-members declared public, the user(the code which instantiates/uses this class) has to totally manipulate the data-members by itself..

class Rect
	int w, h;
	int area;

In above code, if user wants to know the area, he has to keep setting and manipulating the members by himself.. But in a scenario like below,

class Rect
	int w, h;
	int area;
	// area should be first calculated in all the constructors!!!
	// Note: All set-implementations be moved to translational unit

	int Width() const {return w;}
	int Height() const {return h;}
	int GetArea() const {return area;}
	void SetWidth(int w) {this->w = w;
	 area = w * h;}
	void SetHeight(int h) {this->h = h;
	 area = w * h;}
	//void SetArea(int area);// Can't be allowed!!! So, area can't even be public variable

the caller doesn't even need to bother(or we can even say can't come to know because the designer of class Rect intended so..) about how the class Rect's area depends on w and h.. Think of more complicated things with secrecy issues!!
Also, Gettter-setter functions may be attached to some ref-counters to keep track of how many references are their to individual data-members.. This and lots of other purposes for which Getter-Setter are preferred for more complicated data-members which need other things to be updated accordingly.

Through getter setter methods we can indirectly access private data members of the class as shown in the below code. Then what is the significance of encapsulation in OOPS concept. I am not getting the appropiate answer for that. Can anyone help me?

Actually with getters and setters you are not directly accessing them, you are gaining access to their value and a method to alter them through class methods.

This is a subtle but highly significant difference, the actual code that accesses the class memory locations is reduced to a single place (externally to the class at least), the setter/getter. That means that if there is extra operations to do on getting/setting that too can be done in this single place.

Starting from your class supposed that you are in a multi-threaded environment and a decision is made that that class needs to be made thread safe. You simple and some sort of mutex object to the class and acquire it in the getter and setter before getting/setting. Now all the access to the class member is thread safe.

Now suppose that you did not have getters/setters you have public member data accessed directly in code but you have to implement the same change. You will have to find every single instance of access to the class data and add mutex protection calls to it (or implement getters and setters). This is much harder and much more prone to introduction of errors than altering 2 methods.

Getters/setters do the job of encapsulation which is to reduce code complexity, reduce the cost of maintenance and increase the robustness(quality) of the code.

Hi Banfa,
Thanks for reply.
I understood there is advantage of getter-setter methods but according to encapsulation the private member variables of class can not be accessed in main function. But through getter-setter methods we are able to do that, then what is the need of making them private now they are not safe from outside world, anyone can access them even they are private variables.

Private members (whether they be member variables/properties or member functions/methods) are only accessible by other members of the class that contains the private members. For example, class1's private members are only accessible by other members of class1, class2's members and main() are not allowed direct access. To access the members, class2 and main() must use the public interface defined in class1.

What this does is allow you better control over how the data within a specific object/instance of a class is used and manipulated. When you encapsulate the data members within the object, the user/client must use the publicly visible member methods/functions to access them. By requiring that the client code interact with the object's public interface, you can help assure that the data provided in a return value is correct and you can also prevent corruption of your object's current state by dictating the commands the object will accept and the actions it can perform. This dictation gives you the ability to perform multiple coordinated actions when a public method is called, much like tintin.iitk demonstrated above.

But through getter-setter methods we are able to do that, then what is the need of making them private now they are not safe from outside world

They are still "safe". The getter and setter methods don't necessarily just pass the information through in to or out of the private member. For example, what if the value of the private member must be within a specific range? You can put code in your setter method to verify that the new value is within the required range. If it is, you assign the new value. IF it's not, you reject the value and exit the method without performing the assignment such as below...

class example {
    int aPrvInt;
    example(): aPrvInt(0) {}
    bool setAPrvInt(int newInt) {
      //the new value must be between 0 and 10 inclusive to be valid
      if (newInt < 0 || newInt > 10) { 
        cout << newInt << "is an acceptable value..." << endl;
        aPrvInt = newInt;
        return true;
      } else {  //the value is not between 0 and 10
        cout << newInt << "is NOT an acceptable value, please try again..." << endl;
        return false;
      } //end if
    int getAPrvInt () { return aPrvInt; }

No not anyone can access them if they are private only the class can access them. Even if you provide getters and setters still only the class can access them, that is only the class has direct access to the memory they occupy (without some serious doggy pointer manipulation). They are still safe from the outside world because the class designer has control of how they are accessed.

If they are public the class designer has no control in how they are accessed, that is down to the class user (program creator) how they access them.

You are confusing being able to get or alter the value of a data member in a controlled manor through a getter/setter with having direct uncontrolled access.

The job of encapsulation is not to stop the outside world from accessing values it needs to use the class or from setting values it needs to control the class. The purpose of encapsulation is to prevent uncontrolled access which could lead to the class being in an invalid state or containing invalid values. Getters and setters achieve this by putting some code that is under control of the class designer between the outside world and the actual member data (memory) access.

Encapsulation is the hiding of information in order to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer: http://en.wikipedia.org/wiki/C%2B%2B

If you want to take encapsulation for a spin, try and encapsulate a C++ program that does not use classes and all data structures can be accessed by the program.

There is a lot of legacy code out there that needs encapsulation.

Thank you all for reply.
As far as I understood that private member variables can be accessed by its class only. But by getter setter methods they can be accessed under the control of designer.

Correct, getters and setters give you indirect (as opposed to direct) access to the private members.

In providing this indirect access, they give you the ability to control how the data is accessed and manipulated. This control helps protect the data's integrity/quality.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.