8

Why does this work?

#include <stdio.h>

class ClassA
{
public:
    ClassA(int id) : my_id(id) { };

    ClassA * makeNewA(int id)
    {
        ClassA *a = new ClassA(id);
        printf("ClassA made with id %d\n", a->getId());
        return a;
    };

private:
    int getId() {
        return my_id;
    };

private:
    int my_id;
};

int main()
{
    ClassA a(1);
    ClassA *b = a.makeNewA(2);
    return 0;
}

Irrespective of whether or not it's a good idea, why does it work? The public function ClassA::makeNewA(int) instantiates a new ClassA and then calls a private function getId() using the new object. Is a class automatically a friend of itself?

Thanks

Blair Fonville
  • 908
  • 1
  • 11
  • 23

3 Answers3

11

Yes, it is intentional that a class's public methods can access its own private members, even if that method is acting on a different instance.

I guess one could say that a class automatically is a "friend" of itself.

BingsF
  • 1,269
  • 10
  • 15
6

Basically, yes, the class is friend of itself, but better explanation would be that:

In C++ access control works on per-class basis, not on per-object basis.

(copied from there)

Note that this applies also to other languages, for example Java (in which you don't have friends) where access control also works on per-class basis.

Community
  • 1
  • 1
PcAF
  • 1,975
  • 12
  • 20
2

All class methods, static or not, are automatically "friends" of the class. Friend is used to allow external functions and classes access to a class. The class is always its own "friend".

GAVD
  • 1,977
  • 3
  • 22
  • 40