Changing type of object in a conditional

Posted by David Doria on Stack Overflow See other posts from Stack Overflow or by David Doria
Published on 2010-05-28T20:48:01Z Indexed on 2010/05/28 20:52 UTC
Read the original article Hit count: 209

Filed under:
|

I'm having a bit of trouble with dynamic_casting. I need to determine at runtime the type of an object. Here is a demo:

include

include

class PersonClass { public: std::string Name; virtual void test(){}; //it is annoying that this has to be here... };

class LawyerClass : public PersonClass { public: void GoToCourt(){}; };

class DoctorClass : public PersonClass { public: void GoToSurgery(){}; };

int main(int argc, char *argv[]) {

PersonClass* person = new PersonClass; if(true) { person = dynamic_cast(person); } else { person = dynamic_cast(person); }

person->GoToCourt();

return 0; }

I would like to do the above. The only legal way I found to do it is to define all of the objects before hand:

PersonClass* person = new PersonClass; LawyerClass* lawyer; DoctorClass* doctor;

if(true) { lawyer = dynamic_cast(person); } else { doctor = dynamic_cast(person); }

if(true) { lawyer->GoToCourt(); }

The main problem with this (besides having to define a bunch of objects that won't be use) is that I have to change the name of the 'person' variable. Is there a better way?

(I am not allowed to change any of the classes (Person, Lawyer, or Doctor) because they are part of a library that people who will use my code have and won't want to change).

Thanks,

Dave

© Stack Overflow or respective owner

Related posts about dynamic

Related posts about casting