Why are class members private by default?

My book describes it but I dont quite understand.

The reason that class members are private by default is because, in general, an object of a class should be a self-contained entity such that the data that make the object what it is should be encapsulated and only changed under controlled circumstances. Public data members should be very much the exception. As you’ll see a little later in the chapter, though, it’s also possible to place other restrictions on the accessibility of members of a class.

Can someone make it a bit clearer and explain to me please!
Also what does encapsulated mean?
When using a class, it is common practice to use set and get functions to well, set and get the value of said private members. Although, pointers can get you around this concept of private ;)

A class is like a secured fort. You cannot just go in and start changing anything you want. Instead (set and get functions) you must ask for or request that something be changed or given to you.

If you want a public by default data structure, use a struct.
But why? Is there any particular reason?
@Anmol444

Imagine you have a class for geometric object such as a circular arc. Allowing something to change a value of a member variable would invalidate the whole object. For example, if I altered the centre point of the arc & didn't recalc the other variables - the object is now invalid.

So this is why we have access control.

Hope all goes well.

Edit: Michaela Elise I would be interested to see an example of the use of a pointer to get around private access. :)
Last edited on
Oh ok ty
But can you provide a little more detailed explanation please?
In what way? The concept is pretty clear isn't it?
> Why are class members private by default?

I can't see any reason other than that the designer of the language wanted to allow the use of both struct (from C) and class (from Simula 67) as keywords to define a class; and to avoid complete redundancy, decided that:
Members of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default. - IS
TheIdeasMan wrote:
I would be interested to see an example of the use of a pointer to get around private access.


k.

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
33
34
#include <iostream>
#include <cstring>
using namespace std;

class MySecret
{
public:
    MySecret(int n=0, const char* m="") : secret(n)
    {
        if (m) strncpy(message, m, 20);
        else message[0] = 0;
    }
    ~MySecret(){}
private:
    int secret;
    char message[20];
};

int main()
{
    MySecret secret(9, "attack at dawn");

    int *p = reinterpret_cast<int*>(&secret);
    char *s = reinterpret_cast<char*>(&secret);

    cout << p[0] << endl;
    cout << s+sizeof(int) << endl;
    
    p[0] = 13;
    cout << p[0] << endl;

    strcpy(s+sizeof(int), "don't attack us");
    cout << s+sizeof(int) << endl;
}

9
attack at dawn
13
don't attack us
Last edited on
Some other abuses by Herb Sutter:
http://www.gotw.ca/gotw/076.htm
Alright - cool, thanks :)

This is just an observation, not criticism:

Although it seems to be good when the size of the member variables are known, not so good if you have STL containers such as std::string as members.

Cheers.

one more reason not to use char array @.@
This http://www.cplusplus.com/forum/general/98955/#msg532088
as well as every example except #4 in http://www.gotw.ca/gotw/076.htm
leads to undefined behaviour.

And #4 is possible only if the class in question has a template member function.

So,
never subvert the language; for example, never attempt to break encapsulation by copying a class definition and adding a friend declaration, or by providing a local instantiation of a template member function
@Ideasman

So with private control you can only initialize the member and then after never change it? So its only their just to make sure sometimes you don't misuse it like why consts variables exist?
@Anmol444

No, private means that direct access is only granted to member functions of the class. Access applies to variables as well as functions. A class has what is called an interface - public functions which allow interaction with the private member variables. By restricting access to only these functions, one can control what happens. However it is still up to the coder to do the right thing.

For the Arc example - which stores a centre point, radius, start angle, end angle, start point, end point: we want to provide a function that allows us to change the start point of the arc. It is still the responsibility of the coder to ensure that all the others variables are recalculated in this function. This is much better than allowing anything to alter a variable which invalidates the whole object.

About private functions, but first some quick geometry: It is possible to calculate an arc given 3 points on it. Join the 3 points with 2 line segments, the perpendicular bisectors to these line segments (they are normals) intersect at the centre point of the arc. There is quite a bit of calculating to do here, and functions like finding the angle & distance of the line segments shouldn't be part of the public interface, so these functions would be private.

An arc class is an interesting one, there are lots of ways to create a new arc - so there are lots of constructors. There are also lots of ways to modify an arc, so there are lots of functions to allow this. To achieve the overloading of the functions, one has to create classes for all the argument types, because the arguments have to differ by type & number. Further, there are various things like intersections with other arcs & lines, and tests like Point on Arc, Is arc tangential to another arc or line.

The const qualifier is a different thing to private access. It means that the value cannot be changed, and is used for function arguments and return types and for constant values like these:

1
2
const int SIZE = 10; //Array size
const double GRAVITY = 9.8;


I think you would benefit from reading the tutorial on this site - top left of this page.

Hope all goes well.


@Anmol444 Reported you for spamming the forum with repeating questions even when they have been answered in other threads.

Report reason: Asking same question multiple times in multiple threads
Ok thankyou. I will read it and do some more research. But basically its just to prevent misuse of the members.
Topic archived. No new replies allowed.