Access child members within parent class, C++

后端 未结 9 905
南方客
南方客 2020-12-09 06:16

I am facing a situation where I need to access child member variables inside the parent class. I know this is against OO principles but I have to deal with a scenario where

9条回答
  •  误落风尘
    2020-12-09 06:31

    The only clean way is to use the virtual function approach.

    If the Parent class has at least one virtual function (not necessarily DoSomething), there's also a yucky way to do it:

    void DoSomething() {
        if (Child1* child = dynamic_cast(this)) {
            child->childMember = 0;
        } else if (Child2* child = dynamic_cast(this)) {
            child->childMember = 0;
        } // and so on, and so forth
    }
    

    (If Parent has no virtual functions, then the dynamic_cast won't work. Though, any class designed to be inherited from should have at least one virtual function, even if it's just the destructor.)

提交回复
热议问题