Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty class declaration in header file? [duplicate]

Possible Duplicate:
What is forward declaration in c++?

I just have a question about what a piece of code is doing in this simple example. I've looked up friend classes and understand how they work, but I don't understand what the class declaration at the top is actually doing (i.e. Robot). Does this just mean that the Happy class can use Robot objects but they can't access its private parts, any information would be appreciated.

#include <stdlib.h>
#include <stdexcept>

template <typename T>   // What is this called when included 
class Robot;            // is there a special name for defining a class in this way

template <typename T>
class Happy
{ 
  friend class Joe<T>;  
  friend class Robot<Happy<T> >;
  // ...
};
like image 738
Ockham Avatar asked Apr 13 '12 21:04

Ockham


People also ask

How do I stop header file being added twice?

Method. The standard method for preventing a header file from being compiled more than once is to add an include guard. This consists of: a #define directive, which sets a macro when the header is compiled to indicate that it should not be compiled again, and.

What happens if a header file is included twice?

If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice.

Can a header file have multiple classes C++?

That said, there are instances when we have multiple classes in one file. And that is when it's just a private helper class for the main class of the file.


1 Answers

It's a forward declaration.

It's just there to inform the compiler that a class template named Robot will be defined later and that it should expect that definition.

In the meantime (i.e., until Robot is officially defined), it allows the programmer to refer to that type in the code. In the example you've given, it is necessary to declare Robot as a friend of the Happy class. (Who picked these names?!)

It's a common strategy to avoid circular dependencies and minimize compilation time/overhead.

like image 175
Cody Gray Avatar answered Oct 30 '22 23:10

Cody Gray