0

I've been looking at examples for a component-based system and in some of the examples, I noticed the usage of class names outside of other classes like in the example below. What is the purpose/function of creating class Foo; and class Bar; and what is this called?

#pragma once

#include "foo.h"
#include "bar.h"

class Foo; // ???
class Bar; // ???

class Example
{
public:
    Example() :
        m_pExample(0) {}
    virtual ~Example() {}

    void something(const Foo& foo, const Bar& bar);

private:
    Example* m_pExample;
};

3 Answers3

1

It is called a forward declaration and declares class name as a valid but leaves out the definition. This mean that you can use the name as a type before the definition is encountered.

What are forward declarations in C++?

Community
  • 1
  • 1
Leon
  • 12,013
  • 5
  • 36
  • 59
1

Those are called forward declaration

This help the compiler know that the type exists and it knows nothing about its size, members, and methods.

Therefore its a an incomplete type too.

P0W
  • 46,614
  • 9
  • 72
  • 119
0

Actually if you already have #include "foo.h" and #include "bar.h" (assuming the class definition of each class is already in its related .h file), I don't see why you should have the two class Foo; and class Bar; statement.

Usually the reason of putting the class Foo; and class Bar; is that you are going to provide the definition of the two classes yourself.

Example:

#pragma once

class Foo; 
class Bar; 

class Example
{
public:
    Example() :
        m_pExample(0) {}
    virtual ~Example() {}

    void something(const Foo& foo, const Bar& bar);

private:
    Example* m_pExample;
};

class Foo
{
    // Definition of Foo class goes here...
    ;
};

class Bar
{
    // Definition of Bar class goes here...
    ;
};