Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeid not functioning correctly

Tags:

c++

typeid

I cannot get typeid function correctly. Am I missing something

Code:

class A
{
     public:
     int a1;
     A()
    {
    }
};


class B: public A
{
    public:
    int b1;
    B()
    {
    }
};


int main()
{
     B tempb;
     A tempa;
     A * ptempa;
     ptempa = &tempb;

     std::cout << typeid(tempb).name() << std::endl;
     std::cout << typeid(tempa).name() << std::endl;
     std::cout << typeid(*ptempa).name() << std::endl;

     return 0;
}

It always prints:

Class B Class A Class A

I am using VS2010 for my project

like image 435
user2600393 Avatar asked Aug 09 '13 13:08

user2600393


People also ask

What is the use of Typeid () function?

The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.

What does Typeid mean in C++?

The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.

Is Typeid a runtime?

Since typeid is applied to a type rather than an object, there is no runtime type information, so that overhead won't be a problem.


1 Answers

The problem is that A has no virtual functions, so is not treated as a polymorphic type. As a result, typeid looks up the declared type of the pointer, not the actual type of the object that it points to.

like image 161
Pete Becker Avatar answered Nov 06 '22 03:11

Pete Becker