Reputation: 58687
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?
Upvotes: 7
Views: 3889
Reputation: 39419
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.
Upvotes: 1
Reputation: 111946
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.
Upvotes: 4
Reputation: 12481
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.
Upvotes: 3
Reputation: 755141
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);
}
Upvotes: 28