I am trying to have two classes in C - class1, class2. I want class2 to contain an instance of class1 and class1 to have a shared_ptr to the class2 – a pointer to the object, in which it is contained. So I have following 4 files:
class2.hpp
#include "class1.hpp"
#include <vector>
class class2 {
friend class1;
private:
class1 data;
std::vector<int> numbers;
public:
class2();
};
class2.cpp
#include "class2.hpp"
class2::class2() : data(std::shared_ptr<class2>(this)){}
class1.hpp
#include <memory>
class class2;
class class1 {
std::shared_ptr<class2> ptr;
class1(std::shared_ptr<class2> ptr);
void add_item(int i);
};
and class1.cpp
#include "class1.hpp"
class1::class1(std::shared_ptr<class2> ptr) {
ptr = ptr;
}
void class1::add_item(int i) {
ptr->add_item(6); //Member access into incomplete type 'std::__1::shared_ptr<class2>::element_type' (aka 'class2')
}
I am getting the error in function add_item. I think that it has something to do with the forward declaration of class2. I found this related topic, but there they dont split the files into header file. error: member access into incomplete type : forward declaration of
If I understand well, I should put the function add_item after definition of class2, but I dont how to solve it, if I want to have the files splitted like this. Is it possible? Please note, that I am trying to solve this in bigger project, this is very simplified.
Thanks is advance for any answer.
CodePudding user response:
Forward declare class1 in class2.hpp and include class2.h in class1.cpp.
class2.hpp:
//#include "class1.hpp" // REMOVE!
#include <vector>
class class1; // ADD
class class2 {
...
class2.cpp:
#include "class2.hpp"
#include "class1.hpp" // ADD
class1.hpp:
#include <memory>
class class2; // OK
class1.cpp:
#include "class1.hpp"
#include "class2.hpp" // ADD
class1::class1(std::shared_ptr<class2> ptr) {
ptr = ptr;
}
CodePudding user response:
I want class2 to contain an instance of class1 and class1 to have a shared_ptr to the class2 – a pointer to the object, in which it is contained.
No, you should not want that. There is no reason for a sub-object to own (even in shared capacity) their super object.
Furthermore, you cannot access members of an incomplete class. You must define the class first.