I have class B that inherits from A.
class A
{
};
class B : public A
{
};
And I have three objects.
A* a = new A();
A* a2 = new B();
B* b = new B();
I'd like to if check a is object of type A, a2 is object of type B (not A), and b is object of type B.
I tried typed comparison, but it doesn't give me correct answer.
cout << (typeid(*a) == typeid(A)) << endl; // -> 1
cout << (typeid(*a2) == typeid(A)) << endl; // -> 1
cout << (typeid(*b) == typeid(A)) << endl; // -> 0
cout << (typeid(*a) == typeid(B)) << endl; // -> 0
cout << (typeid(*a2) == typeid(B)) << endl; // -> 0
cout << (typeid(*b) == typeid(B)) << endl; // -> 1
I tried dynamic casting, but I got compile error.
B* derived = dynamic_cast<B*>(a);
if (derived) {
cout << "a is B";
}
derived = dynamic_cast<B*>(a2);
if (derived) {
cout << "a2 is B";
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B";
}
typename.cpp: In function 'int main(int, char**)':
typename.cpp:27:36: error: cannot dynamic_cast 'a' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
B* derived = dynamic_cast<B*>(a);
^
typename.cpp:31:34: error: cannot dynamic_cast 'a2' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
derived = dynamic_cast<B*>(a2);
I used static casting, but I got the answer wrong.
B* derived = static_cast<B*>(a);
if (derived) {
cout << "a is B"; // -> YES
}
derived = static_cast<B*>(a2);
if (derived) {
cout << "a2 is B"; // -> YES
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B"; // -> YES
}
How can I correctly identify the object type in C++11?
*a
is of typeA
and*b
is of typeB
per their declaration. – Isochroous