Thread: Comparing polymorphic types

  1. #1

    Comparing polymorphic types

    I have created an abstract type (call it base), and several inherited types (child1..n). I then created an array of base classes.

    I have used this array to store instances of each of the child classes. This all works fine, but I would like to be able to see which one of the child classes is stored in each element of the array. I have tried using the typeid() function, but that comes up with a warning that it can't be used with polymorphic types!

    I could always just add another atribute to the base class that says which one of the child classes it was using, but I am reluctant to do this, purley becasue it seems like a bit of a cop-out! I have also tried messing around with pointers (array of pointers to base class) without any luck! Any ideas?

  2. #2
    You could use something called RTTI - Run Time Type Identification. Use the dynamic_cast operator to get it work.

    subclass *p = dynamic_cast <subclass *> (baseclass);
    if (p)
       some code here..... //its a pointer to subclass
       some code here ....//not a pointer to subclass
    They say that using RTTI is often a sign of bad "codning" (sorry) and insteed of RTTI consider using virtual functions and multiple inheritance insteed.

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Waterloo, Texas
    If the bytecount of each structure of the subclasses is different you may be able to use the sizeof() operator. Not very classy, but it may work:

    if(subClassArr[x] == sizeof(someSubclass) )
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 08-23-2008, 01:16 PM
  2. Comparing Pointer types in C
    By ladesidude in forum C Programming
    Replies: 16
    Last Post: 07-15-2008, 09:34 PM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  4. Replies: 3
    Last Post: 10-31-2005, 12:05 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM