When can I use a forward declaration?

2018-12-30 23:02发布

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. ?

12条回答
旧人旧事旧时光
2楼-- · 2018-12-30 23:31

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.

查看更多
与风俱净
3楼-- · 2018-12-30 23:35

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.

查看更多
零度萤火
4楼-- · 2018-12-30 23:36

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.

查看更多
一个人的天荒地老
5楼-- · 2018-12-30 23:37

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.

查看更多
梦寄多情
6楼-- · 2018-12-30 23:38

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.

查看更多
不流泪的眼
7楼-- · 2018-12-30 23:43

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).

查看更多
登录 后发表回答