Search code examples
c++polymorphismcontainersvirtualadt

ADT and polymorphism


So I have this code:

bool array::InputArray(const ObjectPtr& obj) {
    if(full()) return false;
    if(!duplicate(vet)) throw exception("\nImportant exception");
    obj->input(cin);
    arr[nelem]=obj;
    nelem++;
    return true;
}

obj->input(cin) is just a polymorph function to permit input from console for the exact derived class, the main program gives the right object so that virtual function is not a problem but the arr[nelem]=obj; is, also "arr" is as defined:

object* arr;

My goal is: I want this array to contain the right object when given in the main program, but it only contains the base class side.. how do I tell the compiler to insert even the derived side?? Thanks!


Solution

  • Your code is note quite consistent between the type of obj and the type of arr. Nevertheless, according to the symptoms, your problem is due to object slicing:

    arr[nelem]=obj;
    

    Because, according to your definition of arr, arr[nelem] would be of type object here, which is the base class. So whatever the real derived type of obj, it will be converted back to the base class (and hence use the virtual functions of the base class).

    If you want to have a polymorphic container, you need to have a container of pointers, or better, smart pointers. And instead of arrays, you should really consider using vectors:

    std::vector<std::shared_ptr<Object>> arr;
    
    bool array::InputArray(std::shared_ptr<Object> obj) {
        ...
        obj->input(cin);
        arr.push_back(obj);  // no need for nelem.  Use arr.size() instead
        return true;
    }
    

    Online demo