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);
}
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With