1

I'm in a file that has:

class A; 
class B; 
class C; 

What is the meaning of this where one just states classes?

user4581301
  • 33,082
  • 7
  • 33
  • 54
Prospero
  • 109
  • 1
  • 11
  • 2
    Hi, these are forward declarations. Can you take a look at [this post](https://stackoverflow.com/q/4757565/1424875) and let us know if it answers your question, or whether you have any further doubts? – nanofarad Oct 14 '21 at 19:21
  • 1
    Sometimes the compiler does not need to see a full definition of a class. In this case a forward declaration like yours may speed up compilation. In other cases it may even be necessary, if you don't want to rely on an include order of header files or if there are 2 classes that each use the other one in their respective definitions. – fabian Oct 14 '21 at 19:28
  • The supposed duplicate is quite different -- it asks about forward declarations in general. This question asks about forward declaration of incomplete types, which plays a different role entirely. Please reopen, so I can answer it. – TonyK Oct 14 '21 at 21:37
  • @TonyK Yes please. I'm looking for an in depth explanation on this. – Prospero Oct 15 '21 at 20:17

2 Answers2

1

Suppose a class B contains a pointer to another class M as a member, but none of the members of class M are referenced in the definition of class C:

class C {
  ...
  M* pM ;
  ...
} ;

Then it is not necessary that the complete definition of class M be available to the compiler when class C is defined. But the compiler does need to know that M is a type. This is what such declarations achieve: to make the above code snippet valid, you can simply tell the compiler that M is a class, like so:

class M ;
class C {
  ...
  M* pM ;
  ...
} ;

You can often avoid this by defining your classes in the right order. But if two classes contain pointers to instances of each other, this is the only way to do it:

class B ;
class A {
  ...
  B* pB ; // This would fail without the declaration of `class B`
  ...
} ;
class B {
  ...
  A* pA ;
  ...
} ;
TonyK
  • 16,761
  • 4
  • 37
  • 72
0

It informs the compiler that these classes will be used inside your program. This is named class declaration. It is simmilar to declaring method and then defining it later.

XYZEK 0
  • 13
  • 1
  • 2
  • Thank you. What is the purpose of having them there? Is it so they can be used? For purely clarification purposes? Could you explain more? – Prospero Oct 15 '21 at 20:16