Access child members within parent class, C++

后端 未结 9 909
南方客
南方客 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:40

    Would making an intermediate abstract class that contains the childMember you need to access be an option?

    If so:

    class Parent
    {
        virtual void DoSomething() //Parent must be a polymorphing type to allow dyn_casting
        {
            if (AbstractChild* child = dynamic_cast(this)) {
                child->childMember = 0;
            } else //Its not an AbstractChild
        }
    }
    
    class AbstractChild : Parent 
    { 
    
         int childMember; 
         virtual void DoSomething() = 0;
    }
    
    class Child1 : AbstractChild {
         virtual void DoSomething() { }
    }
    

提交回复
热议问题