3

Assuming I have this code:

class MyClass {
private:    
    class NestedPrivClass {};
public:
     MyClass(NestedPrivClass){}
};

Is there a way for another class to create an instance of MyClass by calling the public constructor?

Shouldn't using private nested class as parameters in public functions be a compilation error? (As it is impossible to call them.)

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • it is not impossible to call it, you just have to get a `NestedPrivClass` by other means – kmdreko Jun 26 '17 at 16:31
  • 1
    What are you trying to do? You could use it like this, for instance: `static MyClass* MyClass::Create() { return new MyClass( NestedPrivClass() ); } ` – zdf Jun 26 '17 at 16:32
  • See ["Why can I use auto on a private type?"](https://stackoverflow.com/questions/13532784/why-can-i-use-auto-on-a-private-type). – zdf Jun 26 '17 at 16:39

1 Answers1

6

No, this should not be an error. Just because the name is private does not mean it is an invalid type. For instance if we added a public static function that returns a NestedPrivClass like

class MyClass {
private:    
    class NestedPrivClass {};
public:
     MyClass(NestedPrivClass){}
     static NestedPrivClass getNestedPrivClass() { return NestedPrivClass{}; }
};

We could then construct a object of MyClass like

int main()
{
    auto private_name = MyClass::getNestedPrivClass();
    MyClass foo{private_name};
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Is that me or is that `auto` circumventing access restriction? Using `MyClass.NestedPrivClass` explicitly where `auto` is used would cause a compilation error, right? –  Jun 26 '17 at 16:42
  • @Arkadiy See: https://stackoverflow.com/questions/13532784/why-can-i-use-auto-on-a-private-type. This is the expected behavior. – NathanOliver Jun 26 '17 at 16:43