Inheritence and usage of dynamic_cast

Posted by Mewzer on Stack Overflow See other posts from Stack Overflow or by Mewzer
Published on 2010-06-17T20:02:45Z Indexed on 2010/06/17 20:13 UTC
Read the original article Hit count: 223

Hello,

Suppose I have 3 classes as follows (as this is an example, it will not compile!):

class Base
{
public:
   Base(){}
   virtual ~Base(){}
   virtual void DoSomething() = 0;
   virtual void DoSomethingElse() = 0;
};

class Derived1
{
public:
   Derived1(){}
   virtual ~Derived1(){}
   virtual void DoSomething(){ ... }
   virtual void DoSomethingElse(){ ... }
   virtual void SpecialD1DoSomething{ ... }
};

class Derived2
{
public:
   Derived2(){}
   virtual ~Derived2(){}
   virtual void DoSomething(){ ... }
   virtual void DoSomethingElse(){ ... }
   virtual void SpecialD2DoSomething{ ... }
};

I want to create an instance of Derived1 or Derived2 depending on some setting that is not available until run-time.

As I cannot determine the derived type until run-time, then do you think the following is bad practice?...

class X
{
public:
   ....

   void GetConfigurationValue()
   {
      ....
      // Get configuration setting, I need a "Derived1"
      b = new Derived1();

      // Now I want to call the special DoSomething for Derived1
      (dynamic_cast<Derived1*>(b))->SpecialD1DoSomething();      
   }
private:
   Base* b;
};

I have generally read that usage of dynamic_cast is bad, but as I said, I don't know which type to create until run-time. Please help!

© Stack Overflow or respective owner

Related posts about c++

Related posts about design