Home > C++, VC++ > Forward declaration

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.

class SomeClass; // Forward declaration
class AnotherClass
{
    protected:
        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.
    class SomeClass;
  2. Inline forward declaration i.e.
    class SomeClass* SomeClassPtr; // Inline forward declaration and use
  3. So if you are forward declaring a struct then instead of class use struct i.e.
    struct SomeStruct;
    struct SomeStruct* SomeStructPtr; // Inline forward declaration and use
  4. You can forward declare a function parameter inline…
    // Forward declared and used inline
    void SomeFunctionUsingSomeClass( class SomeClass* SomeClassPtr );

    Instead of…

    class SomeClass;
    void SomeFunctionUsingSomeClass( SomeClass* SomeClassPtr );
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: