Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define Array of Functions in C++ Class and initialize in ctor?

this is my class:

class Cpu
{
  private:
    typedef uint8_t(Cpu::*OpCode)();
    OpCode *op_codes; // how to define array of 256 function pointers?

    uint8_t op_nop();
    uint8_t op_lxi();
    uint8_t op_stax();
    uint8_t op_mov();
    uint8_t op_mvi();
    ...
};

then I would like to initiate the array in class constructor:

Cpu::Cpu()
{
   op_codes = new OpCode[256] {
            // 0x00
            &Intel8080::op_nop,
            // 0x01
            &Intel8080::op_lxi,
            // 0x02:
            &Intel8080::op_stax,
            // 0x03
     ...
}

and finally I would like to use the array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void Cpu::SingleStep()
    {
        uint8_t op_code = 0x00;
        *op_codes[op_code](); // how to execute the specified function?
    }

Any help will be appreciate. Thanks!

I tried to define the field in the class using various examples.

OpCode op_codes[256];

but how to assign then functions?

>Solution :

You can use std::invoke(with C++17) to make a call using member function pointer. Additionally, it would be better to initialize the array in the member initilizer list instead of assigning to it in the constructor body.

//use member initializer list
Cpu::Cpu(): op_codes(new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax})
{                      
     //this is assignment           
     op_codes = new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax};
}
void Cpu::SingleStep()
{
    uint8_t op_code = 0x00;
    
    //call using std::invoke
    std::invoke(op_codes[op_code], this);

    //old style call without std::invoke
    (this->*op_codes[op_code])();
}

Working demo


can I initialize the array in the ctor body?

We can do assignment inside the ctor body.

Cpu::Cpu()
{                      
     //this is assignment           
     op_codes = new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax};
}

demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading