Mu Qiao
Mu Qiao

Reputation: 7107

Where is type_info object stored?

I read from "Inside The C++ Object Model" that the type_info object is often stored at the first slot of the virtual table. However, I iterated the members in the virtual table:

class Base {
public:
    virtual void f() { cout << "Base::f" << endl; }
    virtual void g() { cout << "Base::g" << endl; }
    virtual void h() { cout << "Base::h" << endl; }
};

typedef void(*Fun)(void);

Base b;

(Fun)*((int*)*(int*)(&b)+0); // Base::f()
(Fun)*((int*)*(int*)(&b)+1); // Base::g()
(Fun)*((int*)*(int*)(&b)+2); // Base::h()

As you see from the last three lines, I can't find type_info at all.

Upvotes: 3

Views: 2425

Answers (3)

JCRunner
JCRunner

Reputation: 145

#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
    public:
        virtual void f() { cout << "Base::f" << endl; }
        virtual void g() { cout << "Base::g" << endl; }
        virtual void h() { cout << "Base::h" << endl; }
};

int main(void)
{
    typedef void(*Fun)(void);
    Fun pFun = NULL;
    Base b;

    pFun = (Fun)(*((long *)(*((long *)(&b))) + 0));
    pFun();//Base::f()
    pFun = (Fun)(*((long *)(*((long *)(&b))) + 1));
    pFun();//Base::g()
    pFun = (Fun)(*((long *)(*((long *)(&b))) + 2));
    pFun();//Base::h()

    type_info *base_type = (type_info *)(*((long *)(*((long *)(&b))) - 1));
    cout << "typeinfo is:" << base_type->name() << endl;

    cout << "the result of typeid(Base).name():" << typeid(Base).name() << endl;
    return 0;
}

the output is:

Base::f
Base::g
Base::h
typeinfo is:4Base
the result of typeid(Base).name():4Base

I use GCC 4.9.2 and my system is 64bit. so I use long instead of int.

type_info object is often stored at the first slot of the virtual table.

This is wrong I think.
type_info object is often stored before the virtual table.
(long *)(*((long *)(&b))):this is the address of virtual table
(long *)(*((long *)(&b))) - 1:this is the address of type_info object
so you see the result of the base_type->name() is 4Base. The result is the same as using typeid.The 4 in 4Base is the number of letters in your class name(Base).more info here

ALSO: when you complie the code with -fdump-class-hierarchy,you could see the Vtable for Base

Vtable for Base
Base::_ZTV4Base: 5u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI4Base)
16    (int (*)(...))Base::f
24    (int (*)(...))Base::g
32    (int (*)(...))Base::h

You could see _ZTI4Base is before Base::f
use c++filt _ZTI4Base would output typeinfo for Base

Upvotes: 1

Nicolae Dascalu
Nicolae Dascalu

Reputation: 3545

type_info is available only if you enable RTTI(runtime type information) compilation flag for some compilers.

Upvotes: -1

Nicol Bolas
Nicol Bolas

Reputation: 474476

There is no cross-compiler way to get at the type_info from the address of an object. Nor would you expect there to be; the way to get a type_info is using a specific C++ keyword: typeid.

Upvotes: 6

Related Questions