Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an array of constructors in C++?

I'm trying to get better at writing C++ code and wanted to know if something like this is possible:

I have 256 instructions in an instruction set. They all have completely different behaviour but with common properties, so I thought about making 256 specific classes that would inherit a common class called Instruction. Then I'd like to store a constructor (or, even, a pair of constructors) for each class into an array of size 256 and simply create the instructions by doing something like: Instruction instr = constructorsOPCode;

Is that possible and is that a good way to approach this problem?

like image 490
An29 Avatar asked Dec 02 '25 06:12

An29


2 Answers

Is it possible to create an array of constructors in C++?

No. A constructor is not an object, so it cannot be element of an array.

It is also not possible to point to a constructor with a function pointer, so an array of function pointers won't be useful. Besides, each constructor would have a different signature, and arrays are homogeneous, so you couldn't store the pointers with the correct type in one array anyway.


inherit a common class called Instruction

and simply create the instructions by doing something like: Instruction instr = constructorsOPCode;

If you create an object of the base class, then it wouldn't be of a derived type, so this cannot work.

It seems like you're trying to invent a polymorphic factory. Something like this could work:

std::unique_ptr<Instruction>
makeInstruction(int op)
{
    switch(op) {
        case 0: return std::make_unique<SomeInstruction>();
        case 1: return std::make_unique<AnotherInstruction>();
        ...
    }
}
like image 75
eerorika Avatar answered Dec 03 '25 22:12

eerorika


No, you can't have an array of constructors, that wouldn't be what you wanted anyway, the constructor just initialises the object, it doesn't create it. You can create an array of factory functions though which create the objects:

std::vector<std::function<std::unique_ptr<Instruction>()>> constructors = 
{
  []{ return std::make_unique<Instruction1>(); },
  []{ return std::make_unique<Instruction2>(); },
  []{ return std::make_unique<Instruction3>(); },
};

std::unique_ptr<Instruction> instruction = constructors[constructorsOPCode]();

Depending on your exact use case shared_ptr may be more appropriate than unique_ptr.

like image 21
Alan Birtles Avatar answered Dec 03 '25 22:12

Alan Birtles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!