Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 357
clx Avatar asked May 25 '13 21:05

clx


People also ask

Can two classes reference each other Java?

A stack overflow has nothing to do with classes referencing each other. It is perfectly possible and supported by Java to do that. The Exception is caused by a too deep recursin, this can happen with one method/class as well. A stack overflow has nothing to do with classes referencing each other.

Can two classes be friends of each other?

Two classes can friend each other; so that they can freely access the private and protected members of the other (I believe the answer is yes, and ofcourse I can simply try it out!). Any detailed references or other question links with answers are also very welcome.


1 Answers

in container.h

class item; // do not include the item.h

in container.cpp

#include "item.h"

in item.h

class container; // do not include container.h

in item.cpp

#include "container.h"
like image 103
Mahmoud Fayez Avatar answered Sep 24 '22 20:09

Mahmoud Fayez