0

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?

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
  • 1
    Think about it: How is the compiler supposed to know what `return in.ib;` means without knowing the definition of `b`? You must define `b` before you define `a::printb`. – Baum mit Augen Mar 12 '16 at 14:36
  • So only declare the subroutines in the classes and then define them later on? – WhatWouldKantDo Mar 12 '16 at 14:38
  • Yep. There is probably a dupe for this, but tbh I do not know how to search for that either. :/ – Baum mit Augen Mar 12 '16 at 14:39
  • 1
    I believe it's called [circular dependency](http://stackoverflow.com/questions/26804803/is-circular-dependency-good-or-bad). In general, it just means a flaw in the design of your program. – Nard Mar 12 '16 at 14:40
  • @BaummitAugen Did not see the public declaration – Nirmal Raj Mar 12 '16 at 14:52

1 Answers1

3

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;
    }
Christophe
  • 68,716
  • 7
  • 72
  • 138
  • The two member functions should probably be marked `inline` to be consistent with the original code. Also necessary if this is in fact a header file. – Pete Becker Mar 12 '16 at 15:11