I am looking for the definition of when I am allowed to do forward declaration of a class in another class's header file:
Am I allowed to do it for a base class, for a class held as a member, for a class passed to member function by reference, etc. ?
Put yourself in the compiler's position: when you forward declare a type, all the compiler knows is that this type exists; it knows nothing about its size, members, or methods. This is why it's called an incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.
Assuming the following forward declaration.
class X;
Here's what you can and cannot do.
What you can do with an incomplete type:
Declare a member to be a pointer or a reference to the incomplete type: class Foo { X *p; X &r; };
Declare functions or methods which accept/return incomplete types: void f1(X); X f2();
Define functions or methods which accept/return pointers/references to the incomplete type (but without using its members): void f3(X*, X&) {} X& f4() {} X* f5() {}
What you cannot do with an incomplete type:
Use it as a base class class Foo : X {} // compiler error!
Use it to declare a member: class Foo { X m; // compiler error! };
Define functions or methods using this type void f1(X x) {} // compiler error! X f2() {} // compiler error!
Use its methods or fields, in fact trying to dereference a variable with incomplete type class Foo { X *m; void method() { m->someMethod(); // compiler error! int i = m->someField; // compiler error! } };
When it comes to templates, there is no absolute rule: whether you can use an incomplete type as a template parameter is dependent on the way the type is used in the template.
For instance, std::vector<T>
requires its parameter to be a complete type, while boost::container::vector<T>
does not. Sometimes, a complete type is required only if you use certain member functions; this is the case for std::unique_ptr<T>
, for example.
A well-documented template should indicate in its documentation all the requirements of its parameters, including whether they need to be complete types or not.
The main rule is that you can only forward-declare classes whose memory layout (and thus member functions and data members) do not need to be known in the file you forward-declare it.
This would rule out base classes and anything but classes used via references and pointers.
Lakos distinguishes between class usage
in-name-only (for which a forward declaration is sufficient) and in-size (for which the class definition is needed).
I've never seen it pronounced more succinctly :)
As well as pointers and references to incomplete types, you can also declare function prototypes that specify parameters and/or return values that are incomplete types. However, you cannot define a function having a parameter or return type that is incomplete, unless it is a pointer or reference.
Examples:
struct X; // Forward declaration of X
void f1(X* px) {} // Legal: can always use a pointer
void f2(X& x) {} // Legal: can always use a reference
X f3(int); // Legal: return value in function prototype
void f4(X); // Legal: parameter in function prototype
void f5(X) {} // ILLEGAL: *definitions* require complete types
None of the answers so far describe when one can use a forward declaration of a class template. So, here it goes.
A class template can be forwarded declared as:
template <typename> struct X;
Following the structure of the accepted answer,
Here's what you can and cannot do.
What you can do with an incomplete type:
Declare a member to be a pointer or a reference to the incomplete type in another class template: template
Declare a member to be a pointer or a reference to one of its incomplete instantiations: class Foo {
X
Declare function templates or member function templates which accept/return incomplete types: template
Declare functions or member functions which accept/return one of its incomplete instantiations: void f1(X
Define function templates or member function templates which accept/return pointers/references to the incomplete type (but without using its members): template
Define functions or methods which accept/return pointers/references to one of its incomplete instantiations (but without using its members): void f3(X
Use it as a base class of another template class template
Use it to declare a member of another class template: template
Define function templates or methods using this type template
What you cannot do with an incomplete type:
Use one of its instantiations as a base class class Foo : X
Use one of its instantiations to declare a member: class Foo {
X
Define functions or methods using one of its instantiations void f1(X
Use the methods or fields of one of its instantiations, in fact trying to dereference a variable with incomplete type class Foo {
X
Create explicit instantiations of the class template template struct X
X
and X<int>
are exactly the same, and only the forward-declaring syntax differs in any substantive way, with all but 1 line of your answer amounting to just taking Luc's and s/X/X<int>/g
? Is that really needed? Or have I missed a tiny detail that's different? It's possible, but I've visually compared a few times and can't see any...
In file in which you use only Pointer or Reference to a class.And no member/member function should be invoked thought those Pointer/ reference.
with class Foo;
//forward declaration
We can declare data members of type Foo* or Foo&.
We can declare (but not define) functions with arguments, and/or return values, of type Foo.
We can declare static data members of type Foo. This is because static data members are defined outside the class definition.
I'm writing this as a separate answer rather than just a comment because I disagree with Luc Touraille's answer, not on the grounds of legality but for robust software and the danger of misinterpretation.
Specifically, I have an issue with the implied contract of what you expect users of your interface to have to know.
If you are returning or accepting reference types, then you are just saying they can pass through a pointer or reference which they may in turn have known only through a forward declaration.
When you are returning an incomplete type X f2();
then you are saying your caller must have the full type specification of X. They need it in order to create the LHS or temporary object at the call site.
Similarly, if you accept an incomplete type, the caller has to have constructed the object which is the parameter. Even if that object was returned as another incomplete type from a function, the call site needs the full declaration. i.e.:
class X; // forward for two legal declarations
X returnsX();
void XAcceptor(X);
XAcepptor( returnsX() ); // X declaration needs to be known here
I think there's an important principle that a header should supply enough information to use it without a dependency requiring other headers. That means header should be able to be included in a compilation unit without causing a compiler error when you use any functions it declares.
Except
If this external dependency is desired behaviour. Instead of using conditional compilation you could have a well-documented requirement for them to supply their own header declaring X. This is an alternative to using #ifdefs and can be a useful way to introduce mocks or other variants. The important distinction being some template techniques where you are explicitly NOT expected to instantiate them, mentioned just so someone doesn't get snarky with me.
I disagree with Luc Touraille's answer
So write him a comment, including a link to a blog post if you need the length. This doesn't answer the question asked. If everyone thought questions about how X works justified answers disagreeing with X doing that or debating limits within which we should restrain our freedom to use X - we'd have almost no real answers.
The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.
As long as you don't need the definition (think pointers and references) you can get away with forward declarations. This is why mostly you'd see them in headers while implementation files typically will pull the header for the appropriate definition(s).
You will usually want to use forward declaration in a classes header file when you want to use the other type (class) as a member of the class. You can not use the forward-declared classes methods in the header file because C++ does not know the definition of that class at that point yet. That's logic you have to move into the .cpp-files, but if you are using template-functions you should reduce them to only the part that uses the template and move that function into the header.
Take it that forward declaration will get your code to compile (obj is created). Linking however (exe creation) will not be successfull unless the definitions are found.
class A; class B { A a; }; int main(){}
, and let me know how that goes. Of course it won't compile. All the proper answers here explain why and the precise, limited contexts in which forward-declaration is valid. You instead have written this about something totally different.
I just want to add one important thing you can do with a forwarded class not mentioned in the answer of Luc Touraille.
What you can do with an incomplete type:
Define functions or methods which accept/return pointers/references to the incomplete type and forward that pointers/references to another function.
void f6(X*) {}
void f7(X&) {}
void f8(X* x_ptr, X& x_ref) { f6(x_ptr); f7(x_ref); }
A module can pass through an object of a forward declared class to another module.
As, Luc Touraille has already explained it very well where to use and not use forward declaration of the class.
I will just add to that why we need to use it.
We should be using Forward declaration wherever possible to avoid the unwanted dependency injection.
As #include
header files are added on multiple files therefore, if we add a header into another header file it will add unwanted dependency injection in various parts of source code which can be avoided by adding #include
header into .cpp
files wherever possible rather than adding to another header file and use class forward declaration wherever possible in header .h
files.
Success story sharing