Topsic
Topsic

Reputation: 109

Call function on some objects in a vector containing different subclasses

I have something like this:

class A {
    void add (A* a) {
        //add a to a vector<A*>
    }
    virtual void draw() = 0;
}

class B : public A {
    void tick() {}
    void draw() {}
}

class C : public A {
    void draw() {}
}

Now what I want to do is have a loop like this:

for(int i=0; i<vector.size(); i++) {
    vector[i]->tick();
}

Problem is that not all the elements in this vector will have the tick() method, but I still want to have them in the same vector because I also want to be able to loop through the vector and call draw() on all the elements. Is there some way to solve this? I'm considering having another vector but I'd rather not.

Upvotes: 0

Views: 267

Answers (2)

kuperspb
kuperspb

Reputation: 339

I think you can use visitor pattern at this case. But it isn't best solution. You brake Liskov substitution principle. Rethink you hierarchy.

Upvotes: 0

John Dibling
John Dibling

Reputation: 101484

If you have a vector of widgets, but only some of those widgets have a dingbat, are they really all widgets?

In your case you have a vector of things that aren't the same. This is your problem. Sure, you could come up with some hacky, complex mechanism to put a battleship in a pencil cup. Or you could do what I'd consider to be one of the Right Things:

  1. Make sure everything you're putting in to the pencil cup is a pencil
  2. Create someplace else to put the battleship.

Number 2 above is creating a seperate vector as you've already mentioned. Number 1 might be as simply as providing a virtual tick() method with an empty (trivial) implementation on the base class.

Upvotes: 5

Related Questions