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> >;
// ...
};
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With