Check object type

I have the code
class A {virtual ~A()};
class B : public A{};
class C : public A();

void func(A *a)
{

}

int main()
{
A *b = new B();
A *c = new C();

func(b);
}

I wanna check which type of a is in func() but i don't know what to do.
Please help me.
I have previously written it to prevent some error
1
2
3
4
5
6
7
8
9
10
11
12
13

template< typename Type, typename DataType >
bool is( const DataType& data ){
	if( &data == NULL ) return false;
    return typeid( data ) == typeid( Type );
}

int func( A *a ){
   if( is<B>( *a ) ){
      // do something
   } 
}


if you don't want to use my function or simply want to avoid template
1
2
3
4
5

int func( A *a ){
    if( typeid( *a ) == typeid( B ) )
}


and
 
#include <typeinfo> 


if the compiler say typeid is not defined or something similar ..
it might fix that problem
Last edited on
> I wanna check which type of a is in func()
void func(A *a)
`a' is of type `A*'
Sorry, I seems to miss interpret the question...
perhaps @ne555 answer is the correct one
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <typeinfo>

class A { public: virtual ~A() = default ; };
class B : public A{};
class C : public A{};

void func( A* a )
{
    if( a != nullptr )
    {
        std::cout << "dynamic type of the object pointed to is: " ;
        
        // http://en.cppreference.com/w/cpp/language/typeid
        const std::type_info& type_info = typeid(*a) ; // typeid on reference to a polymorphic type

        if( type_info == typeid(A) ) std::cout << "A\n" ;
        else if( type_info == typeid(B) ) std::cout << "B\n" ;
        else if( type_info == typeid(C) ) std::cout << "C\n" ;
        else std::cout << "an unknown class derrived from A\n" ;
    }
}

int main()
{
    A a ; A* pa = &a ; func(pa) ; // A
    B b ; pa = &b ; func(pa) ; // B
    C c ; pa = &c ; func(pa) ; // C
    struct D : A {} d ; pa = &d ; func(pa) ; // an unknown class derrived from A
}

http://coliru.stacked-crooked.com/a/4c36fbfc9448c907
You guys are awesome.Thank you alot @JLBorges, @rmxhaha
Topic archived. No new replies allowed.