开发者

Best way to access variables unique to derived class through container of baseclass

So I have a vector of pointers to baseclass, which is used to hold all instances of derived classes.

Base class:

#ifndef BASE_H
#define BASE_H

Class Base
{
  public:

    virtual void DoSomething();

};

#endif

A derived class:

#ifndef DERIVED_H
#define DERIVED_H

#include "base.h"

Class Derived : public Base
{
  public:

    void DoSomething();

    float y;

};

#endif

With these things being stored inside:

std::vector<Base*> theVec;

The question being, what is the best way to access the float variable "y" that exists only in Derived?

I could have a virtual function in Base that is specified in Derived to return a va开发者_如何学JAVAriable, where access looks like:

theVec[0]->GetVar("y");

but when Derived is likely to have multiple variables of different types that are not in base this seems like it will end up being quite messy. Are there any ways to make access to a unique variable in Derived more generic?

Any suggestions would be greatly appreciated!


You use dynamic_cast.

if (Derived* ptr = dynamic_cast<Derived*>(theVec[0])) {
    // do something here
}


There is no elegant solution to this problem. If you have it, your design is probably flawed, and you should rethink it. Having special cases for sub-classes defeats the purpose of polymorphism (although I admit that sometimes it is the only solution).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜