Created
May 12, 2012 04:32
-
-
Save dmikurube/2664136 to your computer and use it in GitHub Desktop.
RTTI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <typeinfo> | |
class Base { | |
public: | |
Base() : x_(0) {} | |
virtual void print() { std::cout << "Base" << std::endl; } | |
private: | |
int x_; | |
}; | |
class Sub : public Base { | |
public: | |
Sub() : y_(0) {} | |
virtual void print() { std::cout << "Sub" << std::endl; } | |
private: | |
int y_; | |
}; | |
class NoVirtualBase { | |
public: | |
NoVirtualBase() : z_(0) {} | |
void print() { std::cout << "NoVirtualBase" << std::endl; } | |
private: | |
int z_; | |
}; | |
class NoVirtualSub: public NoVirtualBase { | |
public: | |
NoVirtualSub() : w_(0) {} | |
void print() { std::cout << "NoVirtualSub" << std::endl; } | |
private: | |
int w_; | |
}; | |
int main() { | |
Base b; | |
Sub s; | |
Base* p = static_cast<Base*>(&s); | |
NoVirtualBase nb; | |
NoVirtualSub ns; | |
NoVirtualBase* np = static_cast<NoVirtualBase*>(&ns); | |
std::cout << typeid( b).name() << std::endl; // 4Base | |
std::cout << typeid( s).name() << std::endl; // 3Sub | |
std::cout << typeid( *p).name() << std::endl; // 3Sub | |
std::cout << typeid( nb).name() << std::endl; // 13NoVirtualBase | |
std::cout << typeid( ns).name() << std::endl; // 12NoVirtualSub | |
std::cout << typeid(*np).name() << std::endl; // 13NoVirtualBase <= It's not NoVirtualSub! | |
std::cout << typeid( &b).name() << std::endl; // P4Base | |
std::cout << typeid( &s).name() << std::endl; // P3Sub | |
std::cout << typeid( p).name() << std::endl; // P4Base | |
std::cout << typeid(&nb).name() << std::endl; // P13NoVirtualBase | |
std::cout << typeid(&ns).name() << std::endl; // P12NoVirtualSub | |
std::cout << typeid( np).name() << std::endl; // P13NoVirtualBase | |
void* vb = &b; | |
void* vs = &s; | |
void* vnb = &nb; | |
void* vns = &ns; | |
std::cout << typeid( vb).name() << std::endl; // Pv | |
std::cout << typeid( vs).name() << std::endl; // Pv | |
std::cout << typeid(vnb).name() << std::endl; // Pv | |
std::cout << typeid(vns).name() << std::endl; // Pv | |
return 0; | |
} |
Same for the latest Clang.
Please look at the line 51 for RTTI and vtables.
typeid() looks type of any "variable" in source code. But, runtime object type is only available in objects with vtables.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comments are gcc's case.