How can two classes uses each other without violating declaration before use? Can you give me an example?

6 Years
Discussion Span
Last Post by mike_2000_17

Only limited way can class A use class B before class B is declared, class A can declare a pointer to an object of class B but that's about the extent of it.

class B; // pre-declare class

class A
   B* b; // declare a pointer to class B


Using a forward-declaration. A forward-declaration is a way to declare a class or function before its full declaration or definition can be written. There are restrictions on how you can use the class or function before its actual declaration or definition appears. In case of a forward-declared class, because the compiler doesn't know what that class is, but only that the class exists (with the promise of a declaration to come), this means that you can only declare pointers or references to that class (i.e. no objects of that class) and you cannot address any of its members. Here is a typical FooBar example:

class Foo; // forward-declaration.

class Bar {
    void do_something(const Foo& f) const; // use the forward-declared class Foo, but only as a reference.

// now, provide the actual declaration of Foo:
class Foo {
    void do_something(const Bar& b) const;

//now that Foo is declared, you can define the member function of Bar:
void Bar::do_something(const Foo& f) const {
  f.do_something(*this); // call the member function of Foo.

Typically, you can use this trick for so-called circular dependencies, like in the above where the definition of Bar depends on the definition of Foo and vice versa. Usually, you put the forward-declaration and declaration of Bar in the header file for Bar (e.g. Bar.h), then you put the declaration of Foo in its own header file (e.g. Foo.h), and finally put the definition of the members of Bar in the source file for Bar (e.g. Bar.cpp) (including the headers for both Bar and Foo, in that order). Forward-declarations can also be used to reduce the amount of header-file dependencies (notice how Bar.h doesn't need to include the header file for Foo, it postpones it to the .cpp file).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.