Joy
Joy

Reputation: 1777

How can I retrieve my derived object added to a collection composed of its superclass objects?

I'm dealing right now with this situation where I have a message object composed of a number of fields so I have a map where I load it with objects of the class Field :

std::map<int,Field*> myMsg;

but in my protocol a field can have sequence as a type, so I created a FieldSequence class which inherits from the Field class, and then to add it to my message I did this:

FieldSequence* seqFld=new FieldSequence(sequence);
myMsg[seqFld->id]=seqFld;

but then I needed to retrieve my field in its original sequence format which I know for sure that its id attribute I set it to 0 value. so I did this:

std::map<int,Field*>::iterator it;
for ( it=myMsg.begin() ; it != myMsg.end(); it++ )
{

    cout << "field id => " << (*it).first <<  endl;
    int idprm=((*it).second)->id;
    if(idprm==0)
    {
        FieldSequence* temp=(*it).second;
    }
}

but I have error due to this Conversion, so what can I do to retrieve my original format or is it gone for good once I add it to my map as it's superclass format?

Upvotes: 1

Views: 62

Answers (2)

tp1
tp1

Reputation: 1207

This is very common problem. The actual problem is not "getting derived class" out of the Field* pointers. The real problem is that your Field class' interface cannot properly represent behaviour of all it's derived classes. One alternative would be this:

class Field {
public:
     virtual std::string ContentsAsString() const=0;
};

Another would be something like this:

class Field {
public:
    virtual char *Buffer() const=0;
    virtual int BufferSize() const=0;
};

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227498

You can use dynamic_cast and check the result:

FieldSequence* temp = dynamic_cast<FieldSequence*>(it->second);
if (temp) { 
  // do stuff
}

But generally this is a sign that you should reconsider the design. It doesn't scale very well if you have many derived types and need to check them all. Containers of pointers to base classes are most powerful when all the derived types implement the same interface and have no additional methods.

Upvotes: 3

Related Questions