Blair Fonville Blair Fonville - 1 year ago 70
C++ Question

Is a class automatically a friend of itself

Why does this work?

#include <stdio.h>

class ClassA
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;

int getId() {
return my_id;

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
instantiates a new ClassA and then calls a private function
using the new object. Is a class automatically a friend of itself?


Answer Source

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.