0

Let's say i have a base class Base, and two derived classA,B How can i dynamically create a obj, without knowing if its ClassA or ClassB, i need to achieve such things like that:

func(Base &b)
{
X *obj = new X();
}

X would be A or B, depends on the actual Type of b.

The only way i can think of so far is to check if dynamic_cast<A&>(b) succeed or not, if an error is thrown, it must be a ClassB.

Is there a better way than that? because i may have more derived classes.ClassA,B,C,D...

henryyao
  • 1,758
  • 6
  • 23
  • 37
  • You don't use the `virtual` keyword often enough. – Hans Passant Aug 07 '15 at 22:42
  • @enryyao You can declare a virtual function create in the base class. – Vlad from Moscow Aug 07 '15 at 22:43
  • 1
    define the interface function as `virtual`, then you can use pointer to base class directly. – luoluo Aug 07 '15 at 22:44
  • @VladfromMoscow correct my if i'm wrong. So i create a virtual function in the Base and derived Classes. This function takes care of generating a new obj and return the pointer to that new obj? And i can call the correct virtual function through parameter b. Is that right? – henryyao Aug 07 '15 at 22:58
  • 1
    @henryyao You are right. Moreover for each derived class the function will have the return type that is the type of the pointer to the derived class. – Vlad from Moscow Aug 07 '15 at 23:05

0 Answers0