Calling a class by the value of a member

Asked

Viewed 89 times

-2

I wonder how I could check if the id of an inherited class is equal to a value x.

Something like:

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

class Y {
    id = 4;
};

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

  • I think more than one instance creation logic is missing. If your classes have no inheritance relation, how do you want to use them later? Even with some logic to create the instances, if there is no inheritance between them, you will not be able to access after...

  • Maybe the code should be class X : A, class Y : A... or else class Y : X.

1 answer

0

The following code will illustrate well how this works, so 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 will understand better how the process works.

To do what you want, you would need some structure{array, vector, list, stack...} with all the instances that inherit this class and after having these instances just iterate over the structure until you find the ones 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 just a basis 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 bit more about this problem is very easy to find better solutions because it depends a lot on what you want with the software.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.