Search code examples
c++classtypesprivateaccess-control

Public function taking private class as parameter


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.)


Solution

  • 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};
    }