Declaration
| Rule 36. Use forward class declarations for classes that are only accessed via pointers (*) or references (&). |
This rule helps to cut down the dependencies between files. C++ allows the forward declaration of a class name without specifying its members and its methods. This is especially useful if a declaration of a function or class only uses references or pointers to another class. Because the internal representation of pointer or reference is independent of the object pointed to, it is enough for the compiler to know a class' name. This in turn means that you do not need to (and according to this rule should not) include the declaration of a class if it is only accessed via pointers or references. The following example explains this:
#include "ClassB.h" // Contains the declaration of class B
class A; // Forward declaration of class A
// C is derived from B, so B's definition is needed,
// but A is only accessed via pointers
class C : public B {
private:
A* m_Pointer;
public:
C();
inline A* getPointer() const;
inline void setPointer(A* );
};
|
There are even some cases of interdependent classes where
a forward declaration of one class is the only possibility
to work around dependencies, like in the following example:
class Queueable;
class Queue {
private:
Queueable* m_Head;
Queueable* m_Tail;
public:
...
};
class Queueable {
friend class Queue;
private:
Queue* m_Queue;
public:
...
};
|
Kaya Memisoglu 2005-01-06
