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

Recommended Answers

All 3 Replies

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
{
public:
   B* b; // declare a pointer to class B


};

So why can't class B have a point to A ie A* a; ?

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 {
  public:
    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 {
  public:
    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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.