1 year ago
#237278
meysamimani
how to solve Invalide use of incomplete type in c++ error
I am trying to understand the reason of the error I get while running main.cpp file. I have two class (foo and gee) included in main.cpp file.
here is the error I get:
foo.cpp: In member function ‘void foo::save(gee&)’:
foo.cpp:13:10: error: invalid use of incomplete type ‘class gee’
13 | i->addfoo(this);
| ^~
foo.h:7:7: note: forward declaration of ‘class gee’
7 | class gee;
|
here is the declaration of foo class(foo.h):
#ifndef foo_H
#define foo_H
#include <set>
#include <string>
class gee;
class foo
{
public:
foo(std::string _str);
void save(gee& geeobj);
private:
std::string str;
std::set<gee*> geelist;
};
#endif
here is the definition of foo class(foo.cpp):
#include "foo.h"
foo::foo(std::string _str)
{
str = _str;
}
void foo::save(gee& geeobj)
{
geelist.insert(&geeobj);
for(auto i:geelist)
{
i->addfoo(this);
// std::cout << "how to run i->addfoo(this); \n"; // this line can be run.
}
return;
}
here is the declaration of gee class(gee.h):
#ifndef gee_H
#define gee_H
#include <set>
#include <string>
class foo;
class gee
{
public:
gee(std::string _name);
void addfoo(foo& _foo_obj);
private:
std::string name;
std::set<foo*> foolist;
};
#endif
here is the definition of gee class(gee.cpp)
#include "gee.h"
gee::gee(std::string _name)
{
name = _name;
}
void gee::addfoo(foo& _foo_obj)
{
foolist.insert(&_foo_obj);
return;
}
and here is the main file(main.cpp)
#include<iostream>
#include "gee.h"
#include "foo.h"
int main()
{
gee gobj("geename");
foo fobj("fooname");
fobj.save(gobj);
return 0;
}
I am also trying to understand the dependency of these files and why I can't execute main.cpp like is it the linker problem can't find the addfoo function body. I thank you if you can give me in addition of the solution, an explanation of why we can't use this.
I am using g++ as compiler and to execute the main.cpp I just type these two line.
g++ gee.h foo.h
g++ main.cpp gee.cpp foo.cpp -o a
c++
class
linker
forward-declaration
0 Answers
Your Answer