Search code examples
c++classforward-declaration

Forward declaration and classes


I am dealing with a situation where I am trying to define two classes that are dependent on each other. This is a simplified example of what I am trying to do.

class a{
public:
    int ia;
    int printb(b in){
        return in.ib;
    }
};

class b{
public:
    int ib;
    int printb(a in){
        return in.ia;
    }
};

This gives me undefined class b errors. I have tried

class b;

class a{
public:
    int ia;
    int printb(b in){
        return in.ib;
    }
};

class b{
public:
    int ib;
    int printb(a in){
        return in.ia;
    }
};

But that does not fixed the problem. Any ideas?


Solution

  • All you have to do is to keep the implementation of the member functions outside the class definition. You can then ensure that both classes are defined before implementing the members:

    class b;
    
    class a{
    public:
        int printb(b in);
        int ia;
    };
    
    class b{
    public:
        int ib;
        int printb(a in);
    };
    
    int a::printb(b in){
            return in.ib;
        }
    int b::printb(a in){
            return in.ia;
        }