-2

I have two classes like below :

class Plot
{
protected:
    virtual void plot() = 0;
}

class DynamicPlot : public Plot
{
public:
    virtual void update_real_time();
    virtual void plot();
}

class StaticPlot : public Plot
{
public:
    virtual void plot();
}

And a container like this:

std::vector<Plot*> plot_vector;

plot_vector.append(new DynamicPlot());
plot_vector.append(new DynamicPlot());
plot_vector.append(new StaticPlot());
plot_vector.append(new StaticPlot());

And i want to call update_real_time() if the type of the instance is DynamicPlot.

foreach(Plot *plot, plot_vector)
{
    if(/* plot type == DynamicPlot */)
    { 
        plot->update_real_time();
    }
    plot->plot();
}

Which pattern should i use here ? Adding an empty update_real_time() method into the StaticPlot class doesn't seem like a good solution.

EDIT : The code above is not real. I just wrote it in order to tell my problem, think that as a psuedo code. I didn't bother to write access qualifiers. In my real code, i do not have a private inheritance or slicing issue. I keep pointers of instances in vector. Sorry for misunderstanding. I am fixing it anyway.

Murat Şeker
  • 1,651
  • 1
  • 16
  • 29
  • 4
    Two problems: 1) your inheritance is private. 2) object slicing. The former is trivial to fix. The latter means you have to store (possibly smart) pointers to `Plot` instead of `Plot` objects. That is before you even start trying to solve the problem you describe. – juanchopanza Aug 03 '13 at 22:48
  • 2
    3) No virtual dtor (a problem in many cases when you store base class pointers). Not a problem now, as you slice the objects, but when you switch to pointers, it'll most probably become a problem. – dyp Aug 03 '13 at 22:50
  • My real code is not like the one that i wrote above. I just wrote it now in order to explain my problem. I ' ll fix it anyway. – Murat Şeker Aug 03 '13 at 22:55

1 Answers1

1

You would need to use dynamic_cast:

foreach(Plot *plot, plot_vector)
{
    DynamicPlot* p = dynamic_cast<DynamicPlot*>(plot);
    if(p)
    { 
        p->update_real_time();
    }
    plot->plot();
}

Except that foreach is not C++, so you would have to use real code for that too.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480