Defining a single class?

I am updating some code, and while I was working in the header, I came across the next line.

. . . class HereIsMyClass; . . . 

What is it. This is just one line that precedes another, longer class definition. HereIsMyClass is actually a different class elsewhere, but I don't understand why this line is written here. What is he doing?

+7
c ++ definition class
source share
4 answers

This line in C ++ is a forward declaration. He states that at some point in the future there will probably be a class called HereIsMyClass. This allows you to use the class in the declaration until it is fully defined.

This is useful for breaking circular dependent classes, and for managing header files.

for example

 class HereIsMyClass; class Foo { void Bar(HereIsMyClass* p1) ... }; class HereIsMyClass { void Function(Foo f1); } 
+27
source share

He called the forward declaration. This tells the compiler that โ€œHereIsMyClassโ€ is the name of the class (compared to a variable name, function, or something else). The class must be defined later for its use.

This is useful if you have classes that must reference each other.

Here is a description .

+4
source share

This is what is called predestination. There is probably a defintion class following this line that uses HereIsMyClass when the actual HereIsMyClass declaration is further in the file or in another #include further included in the file.

If you do not have this line, it is possible that the file will not compile.

+3
source share

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

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

In a direct declaration, the compiler does not say anything about class members, so you still need to include the full class definition (header file) whenever you use it, i.e. e. access to its members.

+1
source share

All Articles