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 <iostream>
#include <string>
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<LawyerClass*>(person);
}
else
{
person = dynamic_cast<DoctorClass*>(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<LawyerClass*>(person);
}
else
{
doctor = dynamic_cast<DoctorClass*>(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