Ok,
Given classes
Base class vBase
and Derived class vLabel and vTextBox
is there a way to determine in the base class which derived class a base class pointer is pointing too?
packetvb
Printable View
Ok,
Given classes
Base class vBase
and Derived class vLabel and vTextBox
is there a way to determine in the base class which derived class a base class pointer is pointing too?
packetvb
Use typeid:For typeid to give the correct type information, the base class must be a polymorphic class; that is, it has at least one virtual member (in your situation, virtual methods are probably already needed).Code:#include <iostream>
#include <typeinfo>
using namespace std;
class base {
public:
// must be polymorphic base class for typeid to work
virtual void something() { };
int a;
};
class derived_a : public base { char b; };
class derived_b : public base { double c; };
int main() {
base *a = new derived_a;
base *b = new derived_b;
base *c = new base;
cout << "typeid(a): " << typeid(a).name() << endl;
cout << "typeid(b): " << typeid(b).name() << endl;
cout << "typeid(c): " << typeid(c).name() << endl;
cout << "typeid(*a): " << typeid(*a).name() << endl;
cout << "typeid(*b): " << typeid(*b).name() << endl;
cout << "typeid(*c): " << typeid(*c).name() << endl;
delete a; delete b; delete c;
}
Note that using typeid on the pointer produces the obvious result that it's a pointer to base. Dereferencing the pointer (here's where the virtual method is needed) looks up the actual type, and sees where it is.
Note that the typeinfo::name() output is *not* portable across compilers...if you wish to verify types, you can use something like:Code:if(typeid(*a) == typeid(derived_a)) { /* lar */ };
Note that you must explicitely enable RTTI for some compilers.