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?

Answers


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;
    }

Need Your Help

Convert java mjpeg stream bytes to an image

java android mjpeg

I'm receiving an mjpeg stream from the WiRC.

ROAR: What are the benefits over jbuilder or rabl?

ruby-on-rails-3 rails-roar

I've read through https://github.com/apotonick/roar and it seems like a lot of thought has been put into ROAR. But in the context of a fairly standard Rails-powered JSON API that uses jbuilder, I'm...