René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Forward declarations in C++

A.h

#ifndef __A__H__
#define __A__H__

#include <string>

class B;  // here is the forward declaration

class A {
public:
  B getBfromA();
  std::string who_are_you();
};


#endif

B.h

#ifndef __B__H__
#define __B__H__

#include <string>

class A;  // Here is the forward declaration

class B {
public:
  A getAfromB();
  std::string who_are_you();
};


#endif

A.cpp

#include "A.h"
#include "B.h"

B A::getBfromA() {
  return B();
}

std::string A::who_are_you() {
  return "I am A";
}

B.cpp

#include "B.h"
#include "A.h"

A B::getAfromB() {
  return A();
}

std::string B::who_are_you() {
  return "I am B";
}

main.cpp

#include "A.h"
#include "B.h"

#include <iostream>

int main() {
  A a;
  B b;

  A ab = b.getAfromB();
  B ba = a.getBfromA();

  std::cout << "ab is: " << ab.who_are_you() << endl;
  std::cout << "ba is: " << ba.who_are_you() << endl;

  return 0;
}