This is due to compiler optimization.
It seems that the compiler should perform such optimization, is a discussion. Do different functions have different addresses? .
Typeid
typeid . , .
if (typeid(*d) == typeid(A))
{
printf("A");
}
else if (typeid(*d) == typeid(B))
{
printf("B");
}
else if (typeid(*d) == typeid(C))
{
printf("C");
}
, /OPT: ICF , , .
/OPT:NOICF , .
, , - , .
#include <string>
struct A
{
virtual std::string getClass() { return A::ID(); }
static std::string ID(){ return "A"; }
};
struct B : public A
{
virtual std::string getClass() { return B::ID(); }
static std::string ID(){ return "B"; }
};
struct C : public A
{
virtual std::string getClass() { return C::ID(); }
static std::string ID(){ return "C"; }
};
int main(int argc, char *argv[])
{
A* d = new C;
if (d->getClass() == A::ID())
{
printf("A");
}
else if (d->getClass() == B::ID())
{
printf("B");
}
else if (d->getClass() == C::ID())
{
printf("C");
}
}