Search code examples
c++publicprotectednested-class

public nested classes inheriting from protected nested classes?


In order to implement my own iterators, I would like to implement something like this :

class MyClass :
{
    public:
        class MyIterator1 {;};
        class MyIterator2 {;};
        class MyIterator3 {;};
};

As these iterators will share some common behaviours, it will be better if they inherit from a base iterator called MyBaseIterator. But I consider MyBaseIterator as a detail of implementation : the user should not use MyClass::MyBaseIterator directly. Is the following OK :

class MyClass :
{
    protected:
        class MyBaseIterator;
    public:
        class MyIterator1 : public MyBaseIterator {;};
        class MyIterator2 : public MyBaseIterator {;};
        class MyIterator3 : public MyBaseIterator {;};
};

Will the member derived from MyBaseIterator be available to the user even if MyBaseIterator is protected ?


Solution

  • Yes, unless the user extends MyClass. To completely deny access, make it private. Also, not that you can only do anything meaningful with MyBaseIterator inside the class (guess you already know that).

    Also, to completely hide implementation details, you should look into the pimpl idiom.