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

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("%cn",(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("%cn",(false?A():B()).test());
    return 0;
}

it can compile, why?


Source: syntax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.