Comparing polymorphic types

This is a discussion on Comparing polymorphic types within the C++ Programming forums, part of the General Programming Boards category; I have created an abstract type (call it base), and several inherited types (child1..n). I then created an array of ...

  1. #1
    Leano
    Guest

    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
    Unregistered
    Guest
    You could use something called RTTI - Run Time Type Identification. Use the dynamic_cast operator to get it work.


    Code:
    subclass *p = dynamic_cast <subclass *> (baseclass);
    if (p)
       some code here..... //its a pointer to subclass
    else
       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
    Location
    Waterloo, Texas
    Posts
    5,708
    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) )
    ....etc
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            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, 02:16 PM
  2. Comparing Pointer types in C
    By ladesidude in forum C Programming
    Replies: 16
    Last Post: 07-15-2008, 10:34 PM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 03: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, 07:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21