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?

Thanks,

Dave

Recommended Answers

All 2 Replies

I don't really understand what your plan is... but if I am correct this should be equivalent and clean:

class PersonClass
{
  public:
  std::string Name;
  virtual void GoToWork(){}; // Or GoToJob, whatever suits you
};

class LawyerClass : public PersonClass
{
  public:
  void GoToWork(){ cout << "Going to Court"; }
};

class DoctorClass : public PersonClass
{
  public:
  void GoToWork(){ cout << "Going to surgery"; }
};

int main()
{
     PersonClass* person = new LawyerClass;
     person->GoToWork();  // prints: Going to Court
}

As long as you reference person through a pointer or a reference it will 'know' that person is a Lawyer.

Besides that you now have a much cleaner interface (same function no matter what type the object is) you also got rid of your dynamic_cast. dynamic_casts really should be used with care, if you think you need it.. think twice: you probably don't.
There are uses of course but mostly there are better alternatives.

Thanks thelamb, that is exactly the behavior I am going for. However, I guess an important part that I failed to mention is that I'm working inside of a library where I cannot change PersonClass (clearly this is all an example, but the equivalent class in the library). Is there any decent way to do it without doing what thelamb suggested?

Thanks,
Dave

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.