Tuesday 22 October 2013

This is why forward declarations important

A lot of people asking me their linker error problem these 2 days during my TA hours. After looking into their code, I noticed the linker error is caused by the circular dependency between the Actor class and ActorController class. This week they need to implement Actor class and ActorController class which is pure interface class.

When the Actor.h
#include "ActorController.h"
class Actor {
    ...
};
and the ActorController.h
#include "Actor.h"
class ActorController {
    ...
};
this is what it called circular dependencies. When compiler compile, it will insert the content of ActorController.h into Actor.h, so Actor.h will become
#include "Actor.h" ---> compiler will insert the content of "Actor.h" here (???)
class ActorController {
    ...
};
class Actor {
    ...
};
Then, it will try to include "Actor.h". This will be endless include loop.

The only way to fix this is by forward declaration. So, the Actor.h will looks like
class ActorController; --> forward declaration
class Actor {
    ...
};
and the "ActorController.h"
class Actor; --> forward declaration
class ActorController {
    ...
};

When we forward-declare the class, we tell the compiler that the class ActorController in Actor.h exists somewhere in the solution world. It is also the same with the ActorController.h. In the end, it is the linker who will link everything together and if it couldn't find either Actor class and ActorController class, it will complain.

One thing to be careful when using forward declaration, though, not every time we can use forward declaration. You can forward declare a class if
1. the compiler doesn't need to know the size of the class during compiler time
2. the compiler doesn't need to access the class' function during compiler time

No comments:

Post a Comment