Whats the point of Privates in classes?

Ive read the privates section in the book. It only explains how to use the privates. It doesnt really explain why you should use privates. I know that only the objects in the class can access the stuff in private. But youre just calling from public to get the private. Which is what I dont get. It just adds more lines of code. Why would I need to write it this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;

class Example
{
public:
void setValue(int y);
int returnPrivate();
private:
int value;
};

int Example::returnPrivate()
{
return value;
}

 void Example::setValue(int y)
{
value = y;
}

int main()
{
    Example Test;
Test.setValue(2);
cout << Test.returnPrivate();
}


Couldnt you just make one function in class Example that returns the value of value?

Please help me out with this.


Last edited on
It does add more lines of code and it does seem like a redundant thing, but, it keeps consistency when dealing with objects since you mostly call methods on them. It helps save you from yourself. It also allows you to clarify what it is you are doing with these variables (hence get and set). The more complex your programs become the more you want readability and to have very "module" code that hides the details of your code. You wouldn't want to hot-wire your car every time you start it (well, most of us don't), instead you just want to turn the key.

Hambone
In your code above there are 2 functions. 1 to set the value and the other o return the value.

>Couldnt you just make one function in class Example that returns the value of value?

Doesn't the value need to be set before being returned?

About private members;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyClass
{
public:
    void manipulateData()
    {
        data = data + 1;
    }
    int data;
};

int main()
{
    MyClass obj;
    obj.data = obj.data - 5;
   return 0;
}


obj has all access (root) access to data and can do all sorts of manipulations on it.
We don't want the kind operation done on data by obj (data = data - 5)
The only manipulation we want on data is provided by manipulateData which does an increment by 1 on the data.

The only way we can enforce this is to make data private by which obj will only access data via manipulateData which follows the conventions we have imposed on data manipulation.

In OOP, A class should have private data which is maniulated by functions, methods or procedures.
Topic archived. No new replies allowed.