Results 1 to 3 of 3

Thread: Is derived class?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2002
    Location
    Okinawa, Japan
    Posts
    271

    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

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    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
  •  



Click Here to Expand Forum to Full Width