Best way to initialize array of base class pointers to array of derived class object instances at compile time?

Viewed 255

I am working on an embedded project where we have support for multiple drivers. Let's say they are audio drivers. I have a base class that models what an audio driver should do and each specific implementation inherits from it:

//AudioBase.hpp
class AudioBase
{
    public:
         virtual void play()=0; // Just a dummy example
};

The main application can use X instances of the derived audio drivers which depend on how many speakers (just for the sake of this example) the hardware has. For this reason, the application has an array of pointers to AudioBase, which points to a specific instance of the audio driver that will be used:

//Application.hpp
#include "AudioBase.hpp"
constexpr unsigned int total_speakers = 20;
class Application
{
    public:
        Application();
    private:
        AudioBase * drivers[total_speakers];
};

I do not have a strong C++ background I would like to ask what would be the best way to initialize statically at compile time the array of drivers with an array of instances of a derived class?

What I am currently doing is that I instantiate all the audio drivers that inherit from AudioBase and based on a macro passed through my build system I conditionally compile the initialization of the array of pointers drivers.

//Application.hpp
#include "Application.cpp"

/*
 All of these objects inherit from AudioBase
Declared as static to avoid dynamic memory allocation
for the embedded target machine.
*/
static DerivedAudio1 driver1[total_speakers];
static DerivedAudio2 driver2[total_speakers];
static DerivedAudio3 driver3[total_speakers];

Application::Application()
{
    for(int i=0;i<total_speakers;i++)
    {
#ifdef DRIVER1
        drivers[i]  = &driver1[I];
#elifdef DRIVER2
        drivers[i]  = &driver2[I];
#elifdef DRIVER3
        drivers[i]  = &driver3[I];
#endif
    }
}

Is this a good solution or are there simpler ways to accomplish this with C++?

0 Answers
Related