Originally I like to use something like this:
(true?a:b).test()
instead of
(true?a.test():b.test())
in order to save typing time if the function has the same name, initially I thought it should be valid, but I found:
#include <stdio.h> class A{ public: char test(){ return 'A'; } }; class B{ public: char test(){ return 'B'; } }; int main(){ printf("%c\n",(false?A():B()).test()); return 0; }
cannot compile, but if B
is subclass of A
:
#include <stdio.h> class A{ public: char test(){ return 'A'; } }; class B : public A{ public: char test(){ return 'B'; } }; int main(){ printf("%c\n",(false?A():B()).test()); return 0; }
it can compile, why?
The reason is that (test?a:b)
is an expression and must have a type. That type is the common type of a and b, and unrelated types have no type in common. The common type of a base and derived class is the base class.
Note that the question contains an assumption that the only case which compiles is where there's a common base type. In fact, it also compiles if there's a unambiguous conversion from one type to the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With