Search code examples
c++inheritanceoutput-parameter

How to us a base class in an output parameter


Say I have code like this:

class B {}
class D : class B {}

void MakeD(int params, D** out, int* status_out);

Today I call it like this:

B* b;
if (use_d) {
  D* d;
  MakeD(params, &d, &status)
  b = d;
} else...

Is there a cleaner way to write this avoiding a separate 'd' object, but without losing the existing type safety (i.e. no reinterpret_cast)?


Solution

  • Is there any reason you can't just modify your MakeD() method to return a new D instead of passing in a pointer to a D?

    ie.

    D* MakeD(int params, int* status_out);
    
    ...
    
    b = MakeD(params, &status);
    

    Or is the MakeD() method a part of someone else's API?