Dago
Dago

Reputation: 1389

How to create a derived class of base class with no virtual methods?

So I have the following situation: I have a (C++) driver that is not in my control that I have the headers and library files for but no source code. I want to simulate the driver in my SW (not just for tests, but use the same code as for the actual implementation). It would be easy to just create a derived class from the base class and re-implement all the methods except none of the methods in the driver base are marked as virtual so I cannot inherit them and still use the same base type in my code. I cannot create a custom header just for the simulation version because I want to be able to use the same code for simulation or real driver. I'm a bit stumped, how do I create a derived class from this non-virtual base?

Upvotes: 0

Views: 130

Answers (1)

If Driver does not offer virtual functions, then having code which uses Driver * use implementations from a class derived from Driver is not possible.

However, you could change your code to be templated by the type of driver use and use two instantiations, one for Driver and one for SimulationDriver (which even wouldn't have to be derived from Driver). Note that in this particular case (where you know all desired instantiations), you can sidestep the usual requirement of "all template code must be in header files" by using explicit instatiation. I use something similar in one of my projects.

Basically, code which currently looks like this:

file.hpp

class Driver;

void process(const Driver *d);

file.cpp

#include "file.hpp"
#include "Driver.h"

void process(const Driver *d)
{
  d->doStuff();
}

will change to look like this:

file.hpp

template <class T_Driver>
void process(const T_Driver *d);

file.cpp

#include "file.hpp"
#include "Driver.h"
#include "SimulationDriver.h"

template <class T_Driver>
void process(const T_Driver *d)
{
  d->doStuff();
}

template void process(const Driver *d);
template void process(const SimulationDriver *d);

Upvotes: 2

Related Questions