c++classnamespaces

two classes using each other under namespace


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!!


Solution

  • 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.