If I have a pointer to a base class A
in C++, how would I be able to tell in my code that the pointer is to a derived class B
or C
?
Asked
Active
Viewed 223 times
0

wrongusername
- 18,564
- 40
- 130
- 214
-
1Is this what you want? http://stackoverflow.com/questions/351845/finding-the-type-of-an-object-in-c – dheerosaur Dec 13 '10 at 07:06
2 Answers
6
Assuming the base class A
is polymorphic (i.e. it has at least one virtual function), you can use dynamic_cast
. Given an A* ap;
:
if (B* bp = dynamic_cast<B*>(ap)) {
// the object is a B
}
else if (C* cp = dynamic_cast<C*>(ap)) {
// the object is a C
}

James McNellis
- 348,265
- 75
- 913
- 977
-
In order to improve readability and avoid 'did you mean "=="' comments from the compiler, I prever `if((blah) != 0)`. Just a matter of taste. – sje397 Dec 13 '10 at 07:11
-
2@sje397: That won't work because `blah` in this case is a declaration, not an expression. Because it is a declaration, the `=` is not `operator=`, and I don't think most compilers would issue a warning here. – James McNellis Dec 13 '10 at 07:12
-
@James: still don't get it - it must evaluate to something 'false' to work as the condition in the `if` yes? – sje397 Dec 13 '10 at 07:22
-
-
I'm with @sje397 here--what does the code mean? It seems like you're trying to assign something. Would the assignment return false if it failed? – wrongusername Dec 13 '10 at 07:34
-
1@sje397 and @wrongusername: if the object is not either the type being cast to or a type derived from the type being cast to, then `dynamic_cast` will return `0` which is evaluated as false. Otherwise it returns a pointer to the object you already have a pointer to, but this pointer will know that it points to an object of the derived type. – Max Lybbert Dec 13 '10 at 08:44
-
1I asked a question to help clarify: http://stackoverflow.com/questions/4427228/assignment-as-condition-adding-parentheses-causes-errors – sje397 Dec 13 '10 at 09:12
2
You generally shouldn't need to know:
struct A {
virtual int generate_foo() = 0;
};
struct B : A {
int generate_foo() { return 42; }
};
struct C : A {
i_;
C(int i) : i_(i) { }
int generate_foo() { return i_++; }
};
If you have an A*
you (1) know that it has a generate_foo()
method, and (2) know that generate_foo()
will generate an appropriate foo for whatever object you really do have. In general that should be enough and you should be able to keep track of when you have an A*
.
Philosophically, the designers of C++ spent years trying to avoid adding runtime type information because it' too easily used incorrectly. However, they eventually decided that they were on the wrong end of a losing battle and added dynamic_cast
and typeinfo()
. C++0x will add more.

Max Lybbert
- 19,717
- 4
- 46
- 69