Calling a class by the value of a member

-2

I would like to know how I could check if the id of an inherited class equals an x value.

Something like:

class X {
    id = 3;
};  ...

class Y {
    id = 4;
};

I have a variant of any x, how could I check if x is equal to the id value of some class and call that instance.

    
asked by anonymous 30.07.2015 / 19:01

1 answer

0

The following code will illustrate how this works, from what I understand, this is what you need to understand the process ...

#include <iostream>

class foo{
    protected:
        int id;
    public:
        foo() : id(9) {}
        virtual void printId(){ printf("%d\n",id); }

};

class oof : public foo{
    public:
        oof(){
            id = 8;
        }
};

class ofo : public foo{
    public:
        ofo() : foo(){}
        void  printId(){std::cout<<id<<"\tOFO"<<std::endl;}
};

class mofu : public ofo{
    public:
        mofu(){
            id = 420;
        }
};

int main(){
    foo * a = new foo();
    foo * b = new oof();
    foo * c = new ofo();
    foo * d = new mofu();
    b->printId();
    a->printId();
    c->printId();
    d->printId();
 return 0;   
}

Once you read it and run it, you'll better understand how the process works.

In order to do what you want, you would need some array {array, vector, list, stack ...} with all the instances that inherit this class and then have these instances just iterate over the structure until you find the what do you want. something like this:

class foo{
    protected:
        int id;
    public:
        foo() : id(9) {}
        virtual void printId(){ printf("%d\n",id); }
        virtual int getId(){ return id; }
};

...
//função que pega um foo * objects[], o tamanho desse array, e um numero para a seleção, e sempre que achar a instancia de 'foo' ele chama o printId();

void selectAndExec(foo ** objects, int arrayLength, int baseArg = 9){
    for(int i = 0; i < arrayLenth; i++){
            if(objects[i]->getId() == baseArg) objects[i]->printId();
    }
}

The default argument is optional, it is only a basis for being able to call the function without passing an id, and it would be 9.

This is one of the ways to do this, if you think a little more about this problem is very easy to find better solutions because it depends a lot on what you want with the software.

    
30.07.2015 / 21:12