What's difference between these codes and why do I have a warning in the second code?
warning: expression with side effects has no effect in an unevaluated context
struct A
{ };
struct B : A
{ };
int main(){
A* temp = new A();
A* temp1 = new B();
std::cout << "B==A : " << (typeid(temp1) == typeid(temp)) << std::endl;
return 0;
}
// .. above code changed just one line:
std::cout << "B==A : " << (typeid(temp1) == typeid(new A())) << std::endl;
I would also like some explain about the warning?
There is no point in writing
typeid(new A()). It is just a more complicated way of writingtypeid(A*).But
typeid(new A())may look as if it will create a newAobject and call its constructor. The expression is however evaluated only if it is a glvalue of polymorphic type, which it isn't here. It is difficult to quickly recognize whether or not the expression is a glvalue of polymorphic type and therefore the compiler may warn you in either case about it if the expression would have side effects. (At least that seems to be what GCC does.)Furthermore
typeid(temp1) == typeid(temp)is also pointless. This simply compares the declared types of the two variables since they are pointer types and will always result intrue, because bothtemp1andtempare of typeA*.Maybe you meant to do
typeid(*temp1) == typeid(*temp). But that will also always result intruehere, sinceAis not a polymorphic type. (It doesn't have any virtual functions.)