Question

I'm having a problem with polymporhic arrays in C++. I have:

    ClassBase **ptr_array = new Base*[dimension]; 

but when I try to do:

     ptr_array[0]=new ChildClass; 
    *ptr_array[0]=ChildIWantToCopy; 

it only copies the attributes of the ClassBase.

Any ideas? Thanks in advance

EDIT: Thankyou very much,unfortunately I can't use references because somehow my array goes crazy and only uses the first position of the array, no matter what. I'll keep researching in it. Thanks again

EDIT2:

When I try to do it like this

    ptr_array[0]=&ChildIWantToCopy;

somehow my array goes crazy, it always copies in the first position. In fact I check the whole array in case the child is already in it before assigning anything, and even if its not in the array it says it is and copies the child, (which shouldn't, because if the child is inside I make it avoid the assignment). This is driving me crazy.

EDIT3: Declarations of the assigntment operators: Class base Client:

    virtual void operator=(Cliente const &cliente); 

ChildClass person:

   void operator=(Persona const &persona);  

ChildClass company:

   void operator=(Empresa const &empresa);
Was it helpful?

Solution

Your polymorphic assignment operator isn't working because the declaration in the derived class is different than the one in the base class. First of all, the assignment operator should return a reference, so change it to:

virtual Cliente &operator=(Cliente const &cliente); 

And then use that SAME declaration in the child classes:

Cliente &operator=(Cliente const &cliente); 

The implementation for a child class will look something like this:

Cliente &Persona::operator=(Cliente const &cliente)
{
    if (this == &cliente)
        return *this;

    //See if the object being copied is another Persona
    const Persona *pOther = dynamic_cast<const Persona *>(&cliente);

    // if pOther is not null, cast was successful
    if (pOther)
    {
        // Copy derived class attributes
        // this->x = pOther->x, etc.
    }

    // Call base class operator=, to copy base class attributes
    return Cliente::operator=(cliente);
}

You can also define a second assignment operator for the derived class, using the derived type (for example, Persona &operator=(Persona const &persona)). But the one which will be used in your example is the one that takes a Cliente const & as a parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top