xcrypt
xcrypt

Reputation: 3386

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

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?

Upvotes: 1

Views: 547

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75150

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.

Upvotes: 3

Related Questions