Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know C++ derived class's base class?

Tags:

c++

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?

like image 670
nick Avatar asked Nov 07 '22 01:11

nick


1 Answers

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

like image 185
Fedor Avatar answered Nov 15 '22 06:11

Fedor