Class declaration and its methods.

Hello Forum,

To avoid circular inclusion with header files, I declare (not define) an user class 'B' at the beginning of the header file of class 'A'.
I can't create an object of 'B' in 'A' (because I only have a declaration), so I create a pointer to 'B' (and set object later).

I guess the order is:
* Declare B (with only the code line "class B;", nothing else).
* Declare A (which includes a 'B' pointer).
* Define A.
- Methods of A include the usage of methods of B, but B is not defined yet.
* Define B (which includes an 'A' object).

But, in the member functions of class 'A', I am allowed to dereference the pointer to 'B', and use the methods of 'B'.
How is this possible? Class 'A' only has the declaration of 'B', right? No definition. So it wouldn't know its methods.
Obviously, my conclusion is incorrect (because it works). Why?

Thank you.

Like this?
A.h declares class B and defines class A.
B.h includes A.h and defines class B.
A.cpp includes A.h and B.h
B.cpp includes B.h
Let's distinguish be tween a forward declaration and a declaration and a definition. A forward declaration just says that the class exists:
class B; // forward declaration
A declaration declares the class and it's members
1
2
3
4
class B {
public:
    void f();
};

A definition defines the code of a method:
void B::f() { cout << "B::f\n"; }

So what you need is:
- Forward declaration of B
- Declaration of A and declaration of B in any order.
- Definition of A and definition of B in any order.
A declaration declares the class and it's members
1
2
3
4
class B {
public:
    void f();
};

No, this is a class definition, even if it doesn't contain the definition of all of its members.
Hello Forum,

Think I get it now.

A.cpp:
#1 = include B.h, with forward declaration of class A:
- Class B can contain a pointer of class A.
- Class B is now defined, but its member functions only declared.
- Member functions of class A are unknown at this point, but that doesn't matter because the member functions of class B are only delcared and not yet defined, so no need to access member functions of class A.
#2 = include A.h, which defines A. I can create a variable of class B in class A, see step #1.
#3 = A.cpp continues and defines all member functions of class A. It knows about class B member functions declarations.

B.cpp:
#1 = include B.h.
#2 = include A.h.
#3 = B.cpp continues...

Thanks for all the replies.
Topic archived. No new replies allowed.