-1

Two class defined, and one is trying to do something using the other. Here is the code:

class_bar.hpp

#ifndef TWOCLASSUSEEACHOTHER_CLASS_BAR_HPP
#define TWOCLASSUSEEACHOTHER_CLASS_BAR_HPP

namespace class_bar
{

class foo;
class bar
{
public:
    foo* getFoo();
    void bar_print();

protected:
    foo* f;
};

}

#endif //TWOCLASSUSEEACHOTHER_CLASS_BAR_HPP

class_foo.hpp

#ifndef TWOCLASSUSEEACHOTHER_CLASS_FOO_HPP
#define TWOCLASSUSEEACHOTHER_CLASS_FOO_HPP

namespace class_foo
{

class bar;
class foo
{
public:
    bar* getBar();
    void foo_print_from_bar();
protected:
    bar* m_b;
};

}

#endif //TWOCLASSUSEEACHOTHER_CLASS_FOO_HPP

class_bar.cpp

#include "../include/class_bar.hpp"
#include "../include/class_foo.hpp"

#include <iostream>

namespace class_bar
{
void bar::bar_print()
{
    std::cout << "bar printing" <<std::endl;
}

}

class_foo.cpp

#include "../include/class_foo.hpp"
#include "../include/class_bar.hpp"

#include <iostream>

namespace class_foo
{
void foo::foo_print_from_bar()
{
    m_b->bar_print(); // compiling error occurs on this line
}

}

The compilor returns error

error: invalid use of incomplete type ‘class class_foo::bar’ m_b->bar_print();

Would like to any suggestions how to deal with this problem. Thank you!!

1

1 Answer 1

3

You forward declare class_foo::bar (as you can see in the eror message) but you want class_bar::bar.

You need the forward declaration in the right namespace:

namespace class_bar {
     class bar;
}

And then inside foo you need to refer to it with the right namespace too: class_bar::bar (rather than just bar). And same for the other class.

2
  • Could you post a little more code? I tried your answer in multiple places with multiple formats, couldn't get it work though. Thank you!! Commented Aug 19 at 14:29
  • @NickXTsui I forgot one detail that needs to be fixed, see update. Otherwise the duplicate Q&As have more information. And look at this tiny example: godbolt.org/z/EhsbTxrz6. Commented Aug 19 at 15:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.