My Class

Commonly used example class name, for editing readability. The discussion below is useless out of context, could someone explain the rest of the page's context? -- JeffBay

That is a little difficult as it is referenced from about 30 pages. -- JohnFletcher

"class MyClass;" here refers to a ForwardDeclaration. This is useful if a method signature includes arguments of type MyClass. The compiler is OK with the method signature because it knows of the existence of MyClass. The file with the method declaration doesn't need to include the actual class declaration because it doesn't need to know any more about the class other than to know it exists. A change in the declaration of MyClass thus won't necessarily require the file containing the method definition to be recompiled.

The CeePlusPlus language standard guarantees that pointers to objects of class type (i.e. pointers to class instances) are always the same size so that the compiler can determine the memory layout of a class containing pointers or references to class objects as members without knowing the concrete implementation of the classes of these objects. The same is true for the signature of functions having pointers or references to class objects as parameters or return value type.

If you're passing class objects by value, or calling member functions of class objects, you need the complete class definition. To make a parameter or variable of a class, the compiler needs to know the size of the object, which it can't determine without the full class declaration.

The most useful thing about it is that you can keep include files from including other include files via this trick. If you use a ForwardDeclaration in your header file (where you define method prototypes that may use it) and include the actual declaration in your source file (where you implement those methods and thus actually use the thing), then other objects that need to include your header file don't need to include the header file of the object you use, thus reducing interdependency. It makes less sense in a language that doesn't separate declaration and definition quite so much.

This technique is mentioned in the ScottMeyers' book EffectiveCeePlusPlus, amongst others. JohnLakos' book LargeScaleCppSoftwareDesign discusses similar techniques to reduce the coupling between header files.
Contributers: NormanNunley?, JeffGrigg, RonJeffries, DebHooker?, TobiasBergemann

View edit of August 4, 2008 or FindPage with title or text search