0

I have to classes, a and b, each needs to have a method that returns the other. If I try to compile the following code, I get an error for not defining the latter class ahead:

class a{
public:
    b* change(){
        return new b;
    }
}
class b{
public:
    a* change(){
        return new a;
    }
}

error: 'b' does not name a type

I understand why, of course, but I want to know if there's a way to implement it correctly.

Oded Sayar
  • 427
  • 1
  • 4
  • 17

2 Answers2

3

Make the definitions of methods after the declarations of classes:

class b;
class a{
public:
    b* change();
}
class b{
public:
    a* change();
}

b* a::change() { return new b; }
a* b::change() { return new a; }

In other words, when you do new T, the definition of T must be available.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • I'd be pedantic and spell out the 2 things you've shown are required: forward-declaration of the classes to provide incomplete types for the method declarations, and full declaration of the classes to provide complete types for constructing (incidentally to return). The requirement for forward-declarations is left implicit in your answer, but it's absolute. – underscore_d Aug 02 '16 at 16:15
  • @underscore_d Be my guest and edit. – Maxim Egorushkin Aug 02 '16 at 16:17
-3

Firstly,. make an object of class b, and then call it. i.e. class b; and then call it in class a.

Malik Nabeel
  • 19
  • 1
  • 13
  • What do you mean? Please show some code illustrating what you're trying to say. _Call_ has 2 possible, very different meanings here, and I think you're getting them mixed up. – underscore_d Aug 02 '16 at 16:08