c++ conditional expression assign reference

Viewed 87
using namespace std;
class A {
    public:
        virtual int r();
};

class B : public A {
    public:
        int r() { return 1; }
};

class C : public A {
    public:
        int r() { return 2;}
};

int main(int argc, char ** argv) {
    B b;
    C c;
    A &a = argc > 1 ? b : c;
    return a.r();
}

with errors:

#g++ a.cc
a.cc: In function ‘int main(int, char**)’:
a.cc:20:18: error: operands to ‘?:’ have different types ‘B’ and ‘C’
   20 |  A &a = argc > 1 ? b : c;
      |         ~~~~~~~~~^~~~~~~

How can I fix it to bind the reference to either of the two objects?

1 Answers

It's just the way the language works, that's all. Note that you can't static_cast from a B to a C either (or vice-versa) which, informally speaking, is required for the branch types of the ternary conditional operator.

You need to write something like

A &a = argc > 1 ? static_cast<A&>(b) : static_cast<A&>(c);
Related