Search code examples
c++forward-declaration

two classes referencing each other


Say there are two classes, which need each other: container and item. The class container creates instances of class item. Each instance of class item holds an instance of class container and needs to call only the method method_called_by_item of class container. Class container needs to see all fields of class item.

The problem is the forward declaration: I want to have a forward declaration inside of item.h, so that the class item can have a container as field and call the method method_called_by_item. How do I do that?

Class container, which creates items.

// container.h
#ifndef CONTAINER_H
#define CONTAINER_H

#include "item.h"

class container{

public:
  item * create_item();
  void method_called_by_item(item * i);
};

#endif //CONTAINER_H

The implementation:

// container.cpp
#include "container.h"

item * container::create_item(){
  return new item(this);
}

void container::method_called_by_item(item * i){
  // do stuff with item
}

The class item, which needs to call one method of container:

// item.h
#ifndef ITEM_H
#define ITEM_H

#include <iostream>

class container;

class item{

public:
  item(container * c);
  void do_something();
  container * c;
};

#endif //ITEM_H

The implementation:

// item.cpp
#include "item.h"

item::item(container * c){
  this->c = c;
}
void item::do_something(){
  this->c->method_called_by_item(this);
}

Solution

  • You have already added the forward declaration to item.h so all you need to do is add the following line to item.cpp.

    #include "container.h"
    

    container.h already includes item.h so you don't have to make any additional changes but as Mahmoud Fayez pointed out you can add a forward declaration there as well. This will remove the dependency on the header file which is typically desired - it can reduce build times on large projects and allows the header file to "stand on it's own".