What is the difference between using #include "stack.h" or using the declaration of this class?

3

Having these two classes, in two different .h files.

um.h

class um {
  //(...)
};

two.h

#include "um.h" //opcao 1

class um; //opcao 2

class dois{
  public:
    void f1(um * p);
};

What is the difference between these two options and which one is the right one?

    
asked by anonymous 18.01.2017 / 02:56

1 answer

5

They are not options, since they do not do the same thing.

When doing #include "um.h" you actually include the class header file (supposedly already defined), so that from then on (in the place where it is including and recursively, if this location is also a header) you have access to all elements of the interface. That is, you can reference an attribute or method of this class - of course, depending on the declared scope and where the reference is being performed.

When you do class um; you just declare the class (that's empty because it has no definition), whose interface must be provided (set) at some point. This is commonly called " forward declaration ", and is useful when you just need to say that you are going to use this class, but you do not need the details of your implementation yet. In other words, you say you will use it, but you do not want (or can not) include the header for some reason.

An example of use is when a class A references a B that references A back. Class A includes the header of B, but class B can only indicate that it "recognizes" class A and thus avoids circular reference in includes :

File b.h:

class A;
class B
{
    A *a;
};

File a.h:

#include "b.h"
class A
{
    B *b;
};

But note that eventually the compiler needs to find the definition of a predefined class (as well as its implementation - the code of the methods), otherwise it will produce compilation and / or linking errors.

    
18.01.2017 / 03:01