Alexv
Alexv

Reputation: 3

Is extern class declaration usage C++ standard compliant?

class My_Container
{
    /*...*/
    class iterator
    {
        extern class const_iterator;
        Node* _ptr;
    public:
        bool operator==(const iterator& other) {return _ptr == other._ptr;}
        bool operator==(const const_iterator& other) {return _ptr == other._ptr;}
    };
    class const_iterator
    {
        Node* _ptr;
    public:
        bool operator==(const const_iterator& other) {return _ptr == other._ptr;}
        bool operator==(const iterator& other) {return _ptr == other._ptr;}
    };
}

It doesn't compile if I omit extern class const_iterator; declaration. It is C++ 17 standard compliant? Can an inner class access to private members of another inner class?

Upvotes: 0

Views: 498

Answers (1)

eerorika
eerorika

Reputation: 238311

Is extern class declaration usage C++ standard compliant?

No, this is not standard compliant. Classes cannot have a storage class specifier.

Can an inner class access to private members of another inner class?

Same way as any other class; it can access public members. The example accesses private member outside of the class, and as such it is ill-formed.

It doesn't compile if I omit extern class const_iterator; declaration.

Use a regular forward declaration instead:

class const_iterator;
class iterator
{
   // ...
};
class const_iterator
{
   // ...
};

I recommend solving the problem another way: Define const_iterator first. Make iterator implicitly convertible to const_iterator. Make const_iterator comparable to only const_iterator.

Upvotes: 1

Related Questions