I have been developing software driver for the SPI I/O expander in the C++ programming language. I have decided to model the registers in the I/O expander in this manner
class Register
{
public:
virtual bool read(void) = 0;
virtual bool write(uint8_t data) = 0;
virtual uint8_t getData(void) = 0;
virtual uint8_t getAddress(void) = 0;
};
template <class T, uint8_t address>
class TypedRegister : public Register
{
public:
TypedRegister::TypedRegister() : reg_address(address){}
bool read(void);
bool write(uint8_t data);
uint8_t getData(void);
uint8_t getAddress(void);
private:
const uint8_t reg_address;
T data;
};
It would be convenient for me to have all the registers in the I/O expander in an array. The problem is that I am not able to define the array in such manner to avoid the dynamic allocation of memory. The array definition
static constexpr uint8_t no_regs_in_expander = 18;
Register register_map[no_regs_in_expander];
does not work because the Register is abstract class so the only one possibility is to define the array in this manner
static constexpr uint8_t no_regs_in_expander = 18;
Register* register_map[no_regs_in_expander];
but it means that I need to create instances of the individual registers via new operator which is prohibited on my platform. Is there any posibility how to achieve a state where all the registers can be in one array and the instances are statically allocated? Thanks in advance for an advice.
TypedRegister<int, 0> obj;pointed to byRegister* ptr = &obj;, and then call virtual functions onptr. In your case, you can useregister_map[0] = &obj;.Registeris abstract is irrelevant - if it weren't you would have "slicing".addressin a member variable.