Thursday, January 20, 2011

Forward Declarations in C++

Using forward declarations in C++ can help to speed up the compilation time.

X.h
#ifndef X_H_
#define X_H_

class Y;

class X
{
public:
    X();
    void doYStuff(Y& y) const;
    void sayHello() const;
    virtual ~X();
};

#endif /* X_H_ */
Here we can use forward declare Y because we don't use any of the Y's members.

X.cpp
#include "X.h"
#include "Y.h"
#include <iostream>
using namespace std;

X::X()
{
}

X::~X()
{
}

void X::sayHello() const
{
    cout << "I'm X!" << endl;
}

void X::doYStuff(Y& y) const
{
    y.sayHello();
}
Here we need to include Y because we use the Y's member.

Y.h
#ifndef Y_H_
#define Y_H_

class X;

class Y
{
public:
    Y();
    void doXStuff(X& x) const;
    void sayHello() const;
    virtual ~Y();
};

#endif /* Y_H_ */
Here we can use forward declare X because we don't use any of the X's members.

Y.cpp
#include "Y.h"
#include "X.h"
#include <iostream>
using namespace std;

Y::Y()
{
}

Y::~Y()
{
}

void Y::sayHello() const
{
    cout << "I'm Y!" << endl;
}


void Y::doXStuff(X& x) const
{
    x.sayHello();
}
Here we need to include X because we use the X's member.

Main.cpp
#include <iostream>
#include "X.h"
#include "Y.h"
using namespace std;

int main()
{
    X x;
    Y y;

    x.doYStuff(y); // I'm Y!
    y.doXStuff(x); // I'm X!

    return 0;
}

No comments:

Post a Comment