A class can be used before it is defined if the compiler doesn't need to know its size. So
Class*
and
Class&
are both OK as long as it's known, at that point, that
Class
is a class. This is often done with a forward declaration that precedes the appearance of
Class
:
class Class;
For
Class*
and
Class&
, the size of
Class
doesn't have to be known because the first is just a pointer, and the second is also (secretly) a pointer. But take away the
*
or the
&
, and
Class
would need to have been defined, not just declared, at that point, because the compiler would need to know how many bytes to set aside for it.
A forward declaration is used to avoid the need for an
#include
. If a header uses
Class
"in name only" (that is, only as a pointer or reference), it can insert the above code rather than
#include "Class.h"
. In a large system, doing this wherever possible can significantly speed up compilation time.
In your example,
newShape
is a factory for creating a
shape
from an existing one, much like a copy constructor. It must therefore be able to reference a
shape
before
shape
has been fully defined.
This can also happen with data members:
class Queueable {
Queueable* next_; };
In your example and this one, a separate forward declaration isn't needed because the class in question is currently being parsed when its name is used.