Sorry for the title's wording; I don't know how to make it better. But the gist of my question is this:
#include <iostream>
using namespace std;
class Base {};
class Base2 {};
class C : public Base, public Base2 {};
class D : public Base {};
void isDerivedFromBase2(Base *p) {
if (...) { /* test whether the "real object" pointed by p is derived from Base2? */
cout << "true" << endl;
}
cout << "false" << endl;
}
int main() {
Base *pc = new C;
Base *pd = new D;
isDerivedFromBase2(pc); // prints "true"
isDerivedFromBase2(pd); // prints "false"
// ... other stuff
}
How do I test if an object, represented by its base class pointer Base *
, is derived from another base class Base2
?
You can perform dynamic_cast
like this:
if (dynamic_cast<Base2 *>(p)) {
online_compiler
Unlike approach with typeid
this one does not require an extra header to be included, however it relies on RTTI as well (this implies that these classes need to be polymorphic).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With