views:

414

answers:

4

I'm updating some code and while I was working in a header, I came across the following line.

.
.
.
class HereIsMyClass;
.
.
.

That's it. It's just one line that precedes another, longer class definition. HereIsMyClass is in fact another class somewhere else, but I don't understand why this line is written here. What does it do?

+25  A: 

This line in C++ is a forward declaration. It's stating that at some point in the future a class named HereIsMyClass will likely exist. It allows for you to use a class in a declaration before it's completely defined.

It's helpful for both breaking up circularly dependent classes and header file management.

For example

class HereIsMyClass;

class Foo { 
  void Bar(HereIsMyClass* p1) ...
};

class HereIsMyClass {
  void Function(Foo f1);
}
JaredPar
+3  A: 

This is what's called a predeclaration. Likely there is a class defintion following this line that uses HereIsMyClass, when the actual declaration of HereIsMyClass is further down in the file, or in another #include included further down in the file.

If you don't have that line, it's possible that the file won't compile.

sheepsimulator
I was surprised: I thought it was called "forward declaration" but google shows about 10 times more hits for predeclaration!
xtofl
I also would have called it "forward declaration". Google shows about 6500 hits only for predeclaration with a German client, and none of the first hits has something to do with programming.
OregonGhost
sheepsimulator
It's not something C or C++ specific. Other languages (pascal) also have this. So the term is not defined by the C++ Standard, but it rather uses it as an already defined thing.
Johannes Schaub - litb
+3  A: 

It's called a "forward declaration". This tells the compiler that 'HereIsMyClass' is the name of a class (versus the name of a variable, a function, or something else). The class will have to be defined later for it to be used.

This is useful when you have classes that need to refer to each other.

Here's one description.

Mr Fooz
+1  A: 

This is called a "forward declaration", which is essentially a promise to define this class later. Having a forward declaration allows you to declare pointers to HereIsMyClass without having to include the header file for it, but not actual objects of it, because the size of an object of HereIsMyClass is still unknown to the compiler.


class HereIsMyClass;

class Foo
{
private:
  HereIsMyClass *pointer; // works
  HereIsMYClass object;   // compiler error!
};

The forward declaration tells the compiler nothing about the members of the class, so you still need to include the full class definition (the header file) whenever you actually use it, i. e. access its members.

Dima