Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Inherit from unknown intermediate class(es) with known base class
    text
    copied!<p>I have an abstract class, called UsbDevice (mostly pure virtual). It doesn't do much, but the three derived classes do:</p> <pre><code>class WindowsUsbDevice : public UsbDevice class LinuxUsbDevice : public UsbDevice class OsxUsbDevice : public UsbDevice </code></pre> <p>each of these classes doesn't really add any public methods - instead they are just different implementations of the UsbDevice abstract class.</p> <p>Now, I want to create a new class that derives from any one of these classes, let's call it FancyUsbDevice. Lets say it represents a specific device.</p> <p>This new class needs to expose the full UsbDevice interface (implemented by the intermediate class), as well as expose a few fancy high-level functions that only use methods on the UsbDevice interface - no need to expose anything specific to one of those intermediate classes.</p> <p>I can see three possible options, and I would like to know if they would work, and which one is the best.</p> <p>A) don't inherit, instead make FancyUsbDevice HAS-A UsbDevice* instead of be IS-A. (sidestep the problem. I don't like this option, but it feels safe.)</p> <p>B) Assuming I have the rare advantage of only having one of those classes actually build on any specific platform, #ifdef the inheritance string: (sidestep the problem again)</p> <pre><code>#ifdef WIN32 class FancyUsbDevice : public WindowsUsbDevice #endif #ifdef LINUX class FancyUsbDevice : public LinuxUsbDevice #endif </code></pre> <p>...</p> <p>C) Templates! Inherit from the template type:</p> <pre><code>Template&lt;typename T&gt; class FancyUsbDevice : public T </code></pre> <p>construct it as the child type, and cast it to the interface:</p> <pre><code>FancyUsbDevice&lt;WindowsUsbDevice&gt; fancy_device; FancyUsbDevice&lt;UsbDevice&gt; generic_fancy_device = dynamic_cast&lt;FancyUsbDevice&lt;UsbDevice&gt;&gt;(fancy_device); </code></pre> <p>however, I don't think that would work, for at least the reason that the compiler will think that generic_fancy_device is smaller than fancy_device, and all of the member variables will be offset and broken. (I think)</p> <p>Thanks! Sorry for using interface / abstract / pure virtual interchangeably. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload