C++ mutually dependent classes -


i have 2 classes represent 2 different data types can converted , forth. want have constructor each takes object of other type can more convert between two, so:

class a{  public:   a(b n){     //do stuff converting n type   } };  class b{  public:   b(a n){     //do stuff converting n type b   } }; 

but fails compile.

if pass b reference, can use incomplete type in a, forward declaration, like:

class b; // forward declaration  class { public:     a() = default;     a(b& n); // declare here  };  class b { public:     b() = default;     b(a n) {         //do stuff converting n type b     } };  a::a(b& n) // define here, b visible {     //do stuff converting n type }  int main() {     a;     b b(a);     another(b); } 

note you'd need default constructors @ least a or b, otherwise cannot create a without b or other way around. declared constructor in a, defined after b visible (thanks @mattmcnabb comment). in way, you'd able use member of b in constructor, since @ point b visible.


Comments