Forward declaration

So what is forward declaration?

It tells a compiler that a particular class name is valid, a declaration and definition of the class will follow soon and don’t worry or give errors about it now.

Remember that compiler will give an error if you invoke any properties or methods of above class, for that you have to give a proper definition because the compiler has to know the size of this class but forward declaration does not provide this information.

This means you cannot use a class object but instead must use a pointer or a reference since pointers and references has a size of 4 (depends on the environment though) this way size of it’s container class be easily determined.

For e.g.

[sourcecode language=’cpp’]class SomeClass; // Forward declaration
class AnotherClass
SomeClass* m_SomeClassPtr; // Compiler is happy.
SomeClass& m_SomeClassRef; // Compiler is happy.
SomeClass m_SomeClassObj; // Compiler gives error, “SomeClass not defined”.

Different ways to forward declare

  1. Normal forward declaration i.e. [sourcecode language=’cpp’]class SomeClass;[/sourcecode]
  2. Inline forward declaration i.e. [sourcecode language=’cpp’]class SomeClass* SomeClassPtr; // Inline forward declaration and use[/sourcecode]
  3. So if you are forward declaring a struct then instead of class use struct i.e. [sourcecode language=’cpp’]struct SomeStruct;
    struct SomeStruct* SomeStructPtr; // Inline forward declaration and use[/sourcecode]
  4. You can forward declare a function parameter inline… [sourcecode language=’cpp’]// Forward declared and used inline
    void SomeFunctionUsingSomeClass( class SomeClass* SomeClassPtr );[/sourcecode]

    Instead of…

    [sourcecode language=’cpp’]class SomeClass;
    void SomeFunctionUsingSomeClass( SomeClass* SomeClassPtr );[/sourcecode]

Appreciate your comments...