user520621
user520621

Reputation:

How do I dynamically allocate memory to a polymorphic data type?

I have a set class that can polymorphically hold and manage anything of type Multinumber. This can be an object of type Pair, Rational, or Complex. The problem that I am running into is that this class requires dynamic memory management and in many cases, such as the function below, I don't know what type to allocate. Since the set is type agnostic, I can't know if I am supposed to do Multinumber* var=new Complex, Rational, or Pair. Is there any way to check the type of what I am adding first, or to store this information in another data type without the slicing effect? One function where I have this problem is this:

bool Set::addElement(Multinumber* newElement)
{
    bool success = false;
    if(isFull())
    {
        resize();
    }
    if(!isMember(newElement))
    {
        setArray[numElements] = newElement;
        numElements++;
        success = true;
    }
    return success;
}

EDIT: I am talking about situations where this is the only place that I could possibly allocate, such as when an operator+ is called and must immediately send the object here, and the calling class does not know what the type is. It happens in my code in the Set operator+ overload, since I the Set doesn't know what it is storing.

Upvotes: 0

Views: 448

Answers (2)

Exia
Exia

Reputation: 21

You can use the typeid operator to check the actual class type of newElement as below:

if (typeid(*newElement) == typeid(Complex))
{
    setArray[numElements] = new Complex;
    // anything else
}

setArray should be an array of Multinumber*.

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61508

I don't see why you would be allocating here. But aside from that, use the virtual clone idiom.

Upvotes: 1

Related Questions