I must refactor an old code. One of its problems is that it exceeds on useless 'includes'. In the same project, I've seen the following syntax:
#include <AnyClass> //A system header
#include "AnotherAnyClass" //A application header
class AnotherClass;
class Class : public OneMoreClass
{
public:
explicit Class();
~Class();
private:
AnotherClass *m_anotherClass;
}
I'd like to figure out:
As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .
A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };
In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.
Declaring a class like this:
class AnotherClass;
is called a Forward Declaration. It lets the compiler know about the existence of the class, in situations where knowning the details about the class aren't needed, like in the scenario you posted.
Generally if you aren't going to be using an instance of the class, you're just dealing with a pointer and not calling any methods on it, you don't need to know anything more than the class name. This can speed up compilation in large projects.
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