1

I like to write my class declarations in a header file and defining it later on: either later on in the header if I want some things to be able to get inlined, or in a cpp. This way I can keep my class declarations tidy and easy on the eye.

However, I want to make a class inside a class (an iterator)

Is it possible to declare it inside a class and define it later on? How?

xcrypt
  • 3,276
  • 5
  • 39
  • 63
  • Related: there's no way to declare the inner class outside the outer class. [c++ - How do I forward declare an inner class? - Stack Overflow](https://stackoverflow.com/questions/1021793/how-do-i-forward-declare-an-inner-class) – user202729 Oct 06 '21 at 00:23

1 Answers1

3

Yes, you just need to add the name of the containing class and then the scope resolution operator, ::, and the name of the inner class, like this

// A.h

class A {
public:
    class B {
    public:
        B() { }

        void dostuff();
    };

    A() { }

    void doStuff();
};

// A.cpp

void A::doStuff() {
    // stuff
}

void A::B::doStuff() {
    // stuff
}

A a;
a.doStuff();

A::B b;
b.doStuff();

There is no (practical) limit to how many nested classes you can have, and you just keep adding :: to go further and further in.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • but it has to be aware of all the methods and members though? I can't just write `class SomeIterator;` inside a class? – xcrypt Dec 21 '11 at 01:23
  • @xcrypt that will be almost the same as `class SomeIterator; class A { ... };` except the forward declaration won't be visible outside class `A`'s declaration. So no, you can't do what the above is doing with just `class SomeIterator;` – Seth Carnegie Dec 21 '11 at 01:25
  • @xcrypt that is like doing `void a() { void b(); }` it doesn't say that the function `b` is inside `a`, it's just a forward declaration of a function that is outside a and is the same as `void b(); void a() { }` except things outside `a` can't see the forward declaration. – Seth Carnegie Dec 21 '11 at 01:28
  • I see. I suppose I have to declare it friend class as well if I want the child class to access the base class's private members/functions? – xcrypt Dec 21 '11 at 01:29
  • @xcrypt yes, just because a class is a nested class does not mean it has access to the outer class's `private`/`protected` variables – Seth Carnegie Dec 21 '11 at 01:32