Saturday 15 August 2015

Difference between include directive and forward declaration in C++ -



Difference between include directive and forward declaration in C++ -

i must refactor old code. 1 of problems exceeds on useless 'includes'. in same project, i've seen next syntax:

#include <anyclass> //a scheme header #include "anotheranyclass" //a application header class anotherclass; class class : public onemoreclass { public: explicit class(); ~class(); private: anotherclass *m_anotherclass; }

i'd figure out:

what differences between 'include "class"' , 'class class'? when should sec method used , how?

those 2 different things:

#include <anyclass>

this normal include header (or type of textual) file. equivalent pasting content of anyclass file in spot typed inclusion directive (that's why include guards and/or compiler pragmas used prevent multiple inclusions in same file).

this syntax:

class anotherclass;

is forward declaration , informs compiler of existence of anotherclass class. useful in many scenarios, e.g. suppose have 2 classes each 1 needs pointer other:

class classb { classa* pointer_to_classa; }; class classa { classb* pointer_to_classb; };

the above code generate error: "error: unknown type name 'classa'" since used classa type without compiler knowing (yet). compiler's parser know classa's existence when parses origin of class declaration.

to have above working need forwards declaration:

class classa; // classa type exists class classb { classa* pointer_to_classa; }; class classa { classb* pointer_to_classb; };

c++

No comments:

Post a Comment