Home > Mobile >  C : What does having keyword class A; class B; class C;, etc. at the beginning of a file accomplish
C : What does having keyword class A; class B; class C;, etc. at the beginning of a file accomplish

Time:10-16

I'm in a file that has:

class A; 
class B; 
class C; 

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

CodePudding user response:

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 ;
  ...
} ;

CodePudding user response:

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.

  • Related