mardi 5 janvier 2021

How avoid error on not evaluated code C++?

Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?

class A {
    //..implementation
    int id() { return 1; }
};

class B {
    //..implementation
    int id() { return 2; }
    bool hasSmth() { return true; }
};

int main() 
{
    auto obj = someFunction();//returns A or B
    if (obj.id() == 1 || (obj.id() == 2 && obj.hasSmth())) {
        ...
    }
}

If the function returns obj of type B, then we are good.
But if it returns obj of type A, compiler will complain about A not having hasSmth, regardless of that part of if never been evaluated.

Can someone give a workaround please?

Aucun commentaire:

Enregistrer un commentaire