Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between include directive and forward declaration in C++

Tags:

c++

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:

  1. What are the differences between a 'include "Class"' and a 'class Class'?
  2. When should the second method be used and how?
like image 289
crissilvaeng Avatar asked Oct 23 '14 14:10

crissilvaeng


People also ask

Should I use forward declaration or include?

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 .

Why use forward declaration instead of include?

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.

What is a forward declaration in C?

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 };

What is forward declaration in Objective C?

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>.


1 Answers

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.

like image 89
Nick Veys Avatar answered Sep 28 '22 05:09

Nick Veys