What would be the advantages to using a forward declaration of a class?
What would be the advantages to using a forward declaration of a class?
I can only think of one, and that is if you had a complex hiearchy of header files. It sort of places a band aid on an organizational problem, and that probably should be addressed in a better way to boot. So the real question is, why are you asking?
Because I'm trying to figure out what any of the advantages would be for a class, and I'd searched my book and it explained how you do it...but not what the advantages would be really and I tried doing several internet searches and board searches to no avail so I decided to just ask and hope that someone who understands it a little better or has maybe actually used it rather than read a little on it would be able to tell me of any advantages they knew of. and Thank You for responding so quickly it's very much appreciated.
When classes reference each other, you have to forward declare one of the class names before you define either of the classesThat's what I learned anyway.Code:class myClassB; class myClassA { void myFunc(const myClassB&); }; class myClassB { void myFunc(const myClassA&); };
Last edited by SlyMaelstrom; 05-03-2006 at 12:39 AM.
Sent from my iPad®
I found a tip that says, quote:But I suggest that you don't follow this either. Compilers are very fast as it is, and this code does nothing but confuse the purpose of A.Suppose you want to define a new class B that uses objects of class A.
1. B only uses references or pointers to A. Use forward declaration then : you don't need to include <A.h>. This will in turn speed a little bit the compilation.
2. B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include <A.h>Code:class A ; class B { private: A* fPtrA ; public: void mymethod(const& A) const ; } ;
It's a hack.
Last edited by whiteflags; 05-03-2006 at 12:47 AM.
Thanks a load guys!!! I really appreciate the help, I got down to like 3 questions left and looked all over and seem to have gotten stumped. I'm so glad for the help.
>> But I suggest that you don't follow this either. Compilers are very fast as it is, and this code does nothing but confuse the purpose of A.
How large are the projects you are compiling? How long do your projects take to compile? For a beginner, the compile times won't matter, but the point is to learn best practice. Once you get into some larger real-world projects, the compile times make a big difference.
>> It's a hack.
No, it's not. Always prefer a forward declaration when it will suffice.
In addition to speeding up compile times and being the only way you can have two classes reference each other, a forward declaration can be useful in maintaining encapsulation.