I found this question When to use forward declaration? which is useful, but it is descriptive not prescriptive.
My scenario is typically I'm using a pointer to another class either as a class member or function argument so all I need in the header is a forward declaration (also as an aside, if I were to switch to using boost shared_ptr's would they be compatible with using forward declarations?). Currently I'm just including the headers but now I'm wondering if I should use forward declarations.
So my question is, if I can use a forward declaration for a class, should I? I'm hoping this question is not subjective, but if there is not a best practice answer then what are the pros/cons of using forward declarations?
UPDATE
Just to expand on the shared_ptr issue (I'm not using them now but considering the switch). If I were to use them I think I'd use the practice of typedef'ing the shared_ptr type inside the class. E.g.:
class Customer
{
public:
typedef std::tr1::shared_ptr<Customer> SharedPointer;
Customer() {}
virtual ~Customer() {}
virtual std::string GetName() const;
};
Seems like that might make things messier. Would that be problematic with forward declaration and if so is there a simple workaround?
You might want to do that because including the files makes the compilation longer, but depending on how many cases you have and how big your code base is, it most likely won't be an issue.
Another thing to consider is the dependencies. You don't want to recompile all your code because of an include file that you changed, when all you need is just the pointer definition.
So my (subjective) answer would be Yes, you should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With