0

How do you test an object to see if it has a certain member? Or is there a way to see if an object is an instance of a certain class?

I'm working with an inheritance structure of character-pictures. There are String_Pics, HCat_Pics, VCat_Pics, and and Frame_Pics. They all derive from Pic_Base. The user uses the handle class "Picture" which contains a smart pointer to the objects. Each object stores a pointer to the picture it's based off (a frame of another picture, two picture horizontally concatenated, etc.).

Ex: A Frame-Pic around a VCat-Pic, and both pics in the VCat-Pic are Frame_Pics around String_Pics.

***************
*             *
* *********** *
* * This    * *
* * is      * *
* *********** *
* *********** *
* * The     * *
* * Example * *
* *********** *
*             *
***************

Frame_Pics have data members for "frame characters," but no other class does. I'm writing a function that will recursively change the frame characters for every frame in the structure. Maybe I'm missing a way to do this otherwise, but I'm looking for a way to test if the object I'm dealing with is a Frame_Pic or not, and thereby whether it would mean anything to try to change the frame characters.

My first instinct was to try something like if (p->frame_char) where frame_char is the name of one of Frame_Pic's data members, but I don't know how to do this.

Andy Isbell
  • 259
  • 1
  • 2
  • 10
  • This has been asked many times before, here is one example with a beautiful solution: http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence – Adam Cadien Jan 16 '13 at 02:43
  • 1
    @AdamCadien I believe that is a compile time solution? Looks like OP needs runtime. – Karthik T Jan 16 '13 at 04:51

2 Answers2

2

You can try to dynamically cast the pointer to a Frame_pic and see if it returns non-null.

Frame_Pic *frame =dynamic_cast<Frame_Pic*>(p);
if(frame  != nullptr){
    //It is Frame_Pic
    frame->frame_char;
}

Not a good idea to go the cast way though.. Try to write virtual functions which do away with the need for it.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

It turned out I really didn't need to do a direct test for membership. This was actually a problem that was a good fit for Polymorphism:

I declared a virtual function "reframe" in Pic_Base and defined the version for "frame" to change the characters, and the ones for the other classes to recurse through the nested pictures as necessary.

Andy Isbell
  • 259
  • 1
  • 2
  • 10