Private access in the public?

Hello. I have a feeling this code should not be permitted, but it seems it is.
Can anyone explain why? Thank you.

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
#include <iostream>

class Dubious
{
    private:

        int stuff;

    public:

        Dubious(int to_steal = 0) : stuff(to_steal) {}

        void steal_stuff(const Dubious &person)
        {
            stuff = person.stuff; // but isn't stuff private?
        }

        void shows_what_hes_got()
        {
            std::cout << stuff << std::endl;
        }
};

int main(int argc, char *argv[])
{
    Dubious person1(330), person2;
    person2.steal_stuff(person1);
    person2.shows_what_hes_got();
    // std::cout << person1.stuff << std::endl;
    // std::cout << person2.stuff << std::endl;

    return 0;
}

Last edited on

but isn't stuff private?


Yes stuff is private.

When a member of a class is private, it means that it is only accessible to Friends to the class and functions of the class itself (which can be either private, public or protected).

It is like this:
An object of type Dubious will have stuff, steal_stuff & shows_what_hes_got.

stuff being private is inaccessible to every thing apart from steal_stuff & shows_what_hes_got.

Now if the two functions decide to show stuff, they can.

But some other function, like main, can't access stuff.


Have a look at this:
http://www.cplusplus.com/doc/tutorial/classes/
&
http://www.cplusplus.com/doc/tutorial/inheritance/
Thanks for your reply.
For anyone interested, I also found this:
http://www.parashift.com/c++-faq-lite/classes-and-objects.html#faq-7.7
Topic archived. No new replies allowed.