'How to construct a certain derived class by calling the base class constructor with a certain argument

So I want to know if its possible to create a certain derived class by constructing the base class with a certain argument. For example:

lets say;

class Base
{
    Base::Base(char derived_selector){...};
}
class DerivedA: public Base
{
   char id_;
   DerivedA::DerivedA(char id):id_(id){};
}

class DerivedB: public Base
{
   int id_;
   DerivedB::DerivedB(int id):id_(id){};
}

Now the reason for inheritance from base here is not clear but since its an example I think it should be fine to understand the realtionship here.

What I want to achieve is when I call

Base *ptrA  = new Base('A');
Base *ptrB  = new Base('B');

The constructor makes the selection of the derived class for me and constructs a DerivedA object for ptrA, and a DerivedB object for ptrB.

I do think there could be some problems like how would the Base constructor know how to set the attributes of the derived class but I feel like it could be achieved somehow. Also if it is indeed possible would this be a good object oriented way or should just decide which one I am making with a simple if else statement when I am going to construct a derived class?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source