Oded Sayar Oded Sayar - 4 months ago 6
C++ Question

Two C++ classes with methods that return the other

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.

Answer

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.

Comments