2

Why can I get an object of a type that is private within a class into an auto variable, and I can call its functions, but only as long as I don't use the actual name?

Example:

#include <iostream>

class A {
    struct B {
        void foo() { std::cout << "foo\n"; }
    };
public:
    struct C {};
    B getB() { return B{}; }
};

// void fB(A::B) { std::cout << "fB\n"; } <-- doesn't compile?
void fC(A::C) { std::cout << "fC\n"; }

int main() {
    A a;
    // A::B b = a.getB(); <-- doesn't compile?
    auto b = a.getB(); // why is this different then the previous line?
    b.foo();
}

The exact error I am getting (with gcc) is: 'struct A::B' is private within this context

Baruch
  • 20,590
  • 28
  • 126
  • 201
  • Not sure what to explain, you just need to accept that it works. You can freely manipulate objects of private types, just not name the types themselves. – HolyBlackCat Jan 19 '22 at 21:45
  • Because `private` only actual makes the name itself private. Uses not involving the name, like `auto`, aren't subject to it. See e.g. [this question](https://stackoverflow.com/questions/64498385/accessing-private-struct-of-a-class-using-auto) – Nathan Pierson Jan 19 '22 at 21:45

0 Answers0