Assume I have a base class A
, and two abstract class B
and C
, and their derived class D
and E
.
How can I distinguish D
and E
's last layer class? (D
's last layer class is B
, E
is C
)
Here is the code:
#include <iostream>
using namespace std;
class ClassA { public: virtual int testFunc() { return 1; } };
class ClassB : public ClassA { public: virtual int testFunc() override =0; };
class ClassC : public ClassA { public: virtual int testFunc() override =0; };
class D : public ClassB { public: virtual int testFunc() override {return 2;} };
class E : public ClassC { public: virtual int testFunc() override {return 3;} };
int main() {
ClassA * d = new D();
ClassA * e = new E(); // !!! how can i know e's last layer class C by pointer e?????
if (somemethod(*e) == somemethod(ClassC)) { // somemethod is what i want
// do something
} else {
// do something
}
}
I know typeid
may help on this, but the code output should be D
and E
, how can I know their last layer class?
It is already in the comments, you can use dynamic_cast
as a replacement of somemethod
in your code as follows:
#include <iostream>
using namespace std;
class ClassA { public: virtual int testFunc() { return 1; } };
class ClassB : public ClassA { public: virtual int testFunc() override =0; };
class ClassC : public ClassA { public: virtual int testFunc() override =0; };
class D : public ClassB { public: virtual int testFunc() override {return 2;} };
class E : public ClassC { public: virtual int testFunc() override {return 3;} };
int main() {
//ClassA * d = new D();
ClassA * e = new E();
if ( dynamic_cast<ClassC*>(e) ) {
std::cout << "classC is among (e) parents";
} else {
std::cout << "classC is not a parent of (e)";
}
}
Demo: https://gcc.godbolt.org/z/TYdPzeMcT
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