|
-
Jun 7th, 2004, 08:47 AM
#1
Thread Starter
Hyperactive Member
Is derived class?
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
-
Jun 7th, 2004, 11:51 AM
#2
Monday Morning Lunatic
Use typeid:
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;
}
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).
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 */ };
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Jun 7th, 2004, 04:21 PM
#3
Note that you must explicitely enable RTTI for some compilers.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|