Shrimp
Shrimp

Reputation: 612

Two derived classes returning each other's type in method

I've got a situation similar to this:

B.hpp

class B {...};

D1.hpp

class D1 : B {
    D2 conversion_method(){ D2 d2(); ... return d2; };
}

D2.hpp

class D2 : B {
    D1 conversion_method(){ D1 d1(); ... return d1; };
}

So those classes need to know each other's definition to return proper types, how would I go about this type of problem? I need those methods to return types (not pointers) because that is the interface requirement.

Upvotes: 0

Views: 36

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

This can be done, but not with inline function declarations.

Both classes need to forward-declare each other, in their header files, i.e.:

class D2;

class D1 : B {
    D2 conversion_method();
}

and

class D1;

class D2 : B {
    D1 conversion_method();
}

Then, somewhere, in some third header file or some .cpp file, which must include both header files, you can define both conversion_method()s, since both classes' definitions are now available.

With some crafty use of additional #includes, and preprocessor macro handling, it would be possible to arrange things so that once both header files get #included, that results in both implementations of conversion_method()s getting defined automatically. This is done by having each header file #define something, and #include a third header file afterwards. The third header file checks if both #defines exist, and proceeds and defines both conversion_method()s. This effectively accomplishes the same thing as your original intention was.

Upvotes: 2

Related Questions