0

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)?

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
Adam Berkan
  • 115
  • 1
  • 6
  • 4
    Instead of using an "out" argument, why not simply return the pointer? – Some programmer dude Nov 19 '12 at 23:55
  • I cannot see any `D` object instantiation here. You are working with undefined pointers. What's happening inside MakeD? – Alessandro Pezzato Nov 19 '12 at 23:55
  • Changing your tags. C doesn't have classes. This is C++ – evanmcdonnal Nov 19 '12 at 23:57
  • 1
    @evanmcdonnal http://programmers.stackexchange.com/questions/48401/learning-c-properly-not-c-with-classes – Luchian Grigore Nov 19 '12 at 23:58
  • @LuchianGrigore Ok, I don't get the point of that. All I read was a bunch of people who probably write terrible C++ code saying how you should use all the awful features of C++ and not just classes. It made me cringe. – evanmcdonnal Nov 20 '12 at 00:02
  • @evanmcdonnal exactly. In my book, the code in the question isn't C++, but C with classes. :) – Luchian Grigore Nov 20 '12 at 00:04
  • Thanks everyone. In my actual code the MakeD runs asynchronously, and fills in `out` at a later time, which makes the obvious "just return D*" answer impossible. But I obviously simplified the question too much. If anyone is still reading, is there any way to do this WITHOUT returning D? – Adam Berkan Nov 20 '12 at 01:01

3 Answers3

1

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?

Hexar
  • 583
  • 2
  • 6
  • In my code, the 'out' is filled in asynchronously, so I can't change MakeD to return it synchronously, but obviously that constraint wasn't formulated in my question. – Adam Berkan Nov 20 '12 at 01:06
0

Why not use basic C++ features such as class constructor and polymorphism: B* b = new D(params);

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
0

Something like

B *b = use_d ? new D(params) : new <something else>; 

should work. I'm assuming the something else is probably a B object (constructed using different parameters maybe?). It needs to be B or a class derived from B for the code to work.

And, as always, don't use a raw B*, instead use

std::unique_ptr<B> ptr( use_d ? new D(params) : new <something else> );
Praetorian
  • 106,671
  • 19
  • 240
  • 328