4

Code with issue:

class A {
    public:
    int i = 2;
};

class B : public A {};
class C : public A {};

int main()
{
    A a;
    B b;
    C c;
    
    auto x = a.i==2 ? c:b;
}

What confuses me, is that when I replace either c orb with a, it seems to recognize that they share a class and will downcast appropriately. So what do I have to do to make this happen here too? I want to avoid an explicit cast to not clutter up the code, but is there any other way?

dockynodyerror
  • 127
  • 1
  • 7
  • You can't "downcast" if it's not a pointer. These types could conceivably have an entirely different stack footprint. – tadman Apr 14 '21 at 03:11
  • 3
    @tadman You can upcast `B` or `C` to `A`, and it would result in [slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). The interesting part of this question is that the type inference engine isn't able to find a common type. My instinct tells me that [`std::common_type`](https://en.cppreference.com/w/cpp/types/common_type) (whose rules are similar to the `?:` operator) may be helpful reading material, but I'm not certain why this doesn't work. – Silvio Mayolo Apr 14 '21 at 03:23
  • @SilvioMayolo interestingly, `std::common_type` doesn't produce a `type` trait: https://godbolt.org/z/dWrqo3vfh – Patrick Roberts Apr 14 '21 at 03:29
  • @SilvioMayolo that's interesting – Aditya Singh Rathore Apr 14 '21 at 03:37
  • Interesting, thanks! Are there any good solutions besides a cast and an if-else expression? – dockynodyerror Apr 14 '21 at 05:39

0 Answers0