Search code examples
c++arraysdereferenceinstances

C++ dereferencing an instance


I'm new to C++ and I'm trying to dry up my code, for example:

void gethit () {
    Gert.hitbox(AA.x, AA.damage);
    Gert.hitbox(AB.x, AB.damage);
    Gert.hitbox(AC.x, AC.damage);
    Gert.hitbox(AD.x, AD.damage);
    Gert.hitbox(Terbil.x, Terbil.damage);
}

AA, AB, AC, AD and Terbil are all instances of a class called Entity with variables x and damage.

Every time I want to add a new instance I'll have to come into this function and add it manually. I'm trying to add all of the address of the instances to an array like so:

void * p_enemys[10];

p_enemys[0] = &AA;
p_enemys[1] = &AB;
p_enemys[2] = ∾
p_enemys[3] = &AD;
p_enemys[4] = &Terbil;

Just wondering how I could call a function from the instance via the array, I tried to do

for(int i = 0; i < 10; i++;) {
    Gert.hitbox(p_enemys[i].x, p_enemys[i].damage);
}

and g++ compiler spits out: "request for member `damage' in `p_enemys[i]', which is of non-aggregate type `void *'"

I don't really need to use arrays specifically any help is very appreciated.

Changes made, thanks @gldraphael!

vector <Entity*> p_Enemys(10);

void gethit () {
    for (int i = 0; i < 10; ++i) {
    Entity * ienemy = (Entity*) p_Enemys[i];
        Gert.hitbox((ienemy->x), (ienemy->damage));
    }
}

Solution

  • You can make an a std::vector as follows:

    std::vector <Entity*> p_Enemys(10);
    

    The assigning part remains the same:

    p_enemys[0] = &AA;
    p_enemys[1] = &AB;
    p_enemys[2] = &AC;
    p_enemys[3] = &AD;
    p_enemys[4] = &Terbil;
    

    You can then loop through the p_enemys as follows:

    for(auto i : p_enemys) {
        Gert.hitbox(i->x, i->damage);
    }
    

    So what was it that you missed?
    The array was declared as an array of void* So, in the loop, p_enemys[i] returned a void*.

    Also class/struct members are accessed using a dereferencing operator ->. You used the membership operator . instead.

    So this code should have worked instead:

    for(int i = 0; i < p_enemys.size(); i++;) {     // 
        Entity * ienemy = (Entity*) p_enemys[i];    // cast the void* into a Entity*
        Gert.hitbox(ienemy->x, ienemy->damage);
    }
    


    As a general rule, avoid void*s whenever possible.