Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can (false?A():B()).test() compile only when A and B have a subclass relationship?

Tags:

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?

like image 722
ggrr Avatar asked Jul 14 '15 07:07

ggrr


1 Answers

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.

like image 114
MSalters Avatar answered Oct 07 '22 15:10

MSalters