Access member variables of derived class object po

2019-07-30 15:27发布

I have one base class and two classes derived from it. I have several virtual functions in the base class so I create a pointer to the base class and use this pointer to access these methods.

Now I want to access member variable of derived class (this variable is not present in the base class) using the pointer to base class which points to a derived class object.

Can this be done? Should this be done?

4条回答
▲ chillily
2楼-- · 2019-07-30 15:56

Yes you can do it, but it is not recommended. You can use dynamic_cast to cast the base class pointer to the derived class pointer and get the variables in the derived class.

For example, if you have a base clas called Base and two derived classes Derived1 and Derived2, and if you have Base* p pointer then you can do:

Derived1* d1 = dynamic_cast<Derived1*>(p);
查看更多
何必那么认真
3楼-- · 2019-07-30 15:58

Why do you want to access the derived class' interface? When you use polymorphism, you shouldn't need to care about what's behind a base class reference/pointer. If you do, then that's usually a hint at a design flaw.

What you are trying to do is a "switch-on-type". ("If behind B* is a D1 object, do this, otherwise do that".) A switch-on-type is circumventing polymorphism and a bad sign.

Note: There is a way to do this (dynamic_cast), but for the reasons mentioned above I consider this bad practice and won't elaborate on it.

查看更多
仙女界的扛把子
4楼-- · 2019-07-30 15:59

Just move that variable to the base class. The only case when Base class need to call methods (or to use variables) of Derived class is Curiously recurring template pattern when it implements static polymorphism. In other cases it looks like bad design.

查看更多
Emotional °昔
5楼-- · 2019-07-30 16:09

Write a virtual function, that would act accordingly in each of the classes, and in the place where you actually "need" to access the variable - call that function. It's that simple.

查看更多
登录 后发表回答