1

Consider the following code:

struct A{
private:
    struct B{};
public:
    B make() const{return B{};}
};

int main(){
    A a; 
    auto b1 = a.make(); (void)b1;
//  A::B b2 = a.make(); (void)b2; // compile error: B is a private class
}

What is the logic behind being able to compile b1 line while the second b2 line? After all auto is supposed equivalent to replace the name of the class.

If it is what I think, this shows that auto is not simply syntax sugar. auto on private classes can be used force the user not know about certain types but still be able to use instance of them! (and this was not possible in C++98?)

Am I mistaken in this interpretation?

alfC
  • 14,261
  • 4
  • 67
  • 118
  • 1
    You are right in your assessment of the situation. I have seen a question on SO regarding that. The main point is that the name `A::B` is `private` but not the type, if that makes sense. I'll try to find the duplicate. – R Sahu Nov 12 '18 at 02:54
  • 2
    https://stackoverflow.com/questions/13532784/why-can-i-use-auto-on-a-private-type – rmawatson Nov 12 '18 at 02:55
  • @RSahu, thanks. I find interesting that this was no possible in C++98. – alfC Nov 12 '18 at 03:21
  • 1
    @alfC, in C++98, it was possible to access the type in the sense that you could use the `public` member functions/variables of the returned object without assigning it to a variable. Somethink like `a.make().b_func()`. – R Sahu Nov 12 '18 at 03:26

0 Answers0