-5

Suppose we have two classes Foo and Bar. We can declare the Foo class and use its methods as following:

#include"foo.h"

Foo foo

class Bar{
    Bar(){
        foo.method1();
    }
}

And we have the forward declaration, which stands to declare the Foo class as following:

#include"foo.h"

class Foo

class Bar{
    Bar(){
    }
}

What are the main differences between the two declartions, and when the forward declaration is prefered to the normal declaration?

ch4d0w
  • 13
  • 4
  • Useful link : https://www.quora.com/What-exactly-is-the-difference-between-the-declaration-of-a-class-and-a-definition-of-a-class – msc Sep 28 '16 at 08:17
  • in your second example `Foo` is never used, so I don't understand your question – bolov Sep 28 '16 at 08:18
  • 1
    Possible duplicate of [C++ - Forward declaration](http://stackoverflow.com/questions/4757565/c-forward-declaration) – dkg Sep 28 '16 at 08:18
  • 3
    "*We can declare the Foo class and use its methods*" Maybe try compiling your first code sample? – juanchopanza Sep 28 '16 at 08:19

1 Answers1

1

In second case you don't need

#include"foo.h"

In forward declaration you just say compiler "There are Foo class somewhere. But I don't know how it look". So compiler can refer them but can't use them;

class Foo; //Forward declaration.

Foo* foo; // ok. Just pointer.
Foo foo;// error. Compiler can't instantiate object.

and

#include "foo.h"

Foo* foo; // ok. Just pointer.
Foo foo;// ok. Compiler can instantiate object.

So, in some case forward declaration can replace the inclusion of a header file.

Konstantin T.
  • 994
  • 8
  • 22