Access child members within parent class, C++

后端 未结 9 833
南方客
南方客 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<AbstractChild*>(this)) {
                child->childMember = 0;
            } else //Its not an AbstractChild
        }
    }
    
    class AbstractChild : Parent 
    { 
    
         int childMember; 
         virtual void DoSomething() = 0;
    }
    
    class Child1 : AbstractChild {
         virtual void DoSomething() { }
    }
    
    0 讨论(0)
  • 2020-12-09 06:42

    static_cast<Child*>(this)->childMember = 0; should work.

    0 讨论(0)
  • 2020-12-09 06:44

    You can use the curiously recurring template pattern to achieve this.

    template<typename T>
    class Parent
    {
        void DoSomething()
        {
            // This is what I need
            T::childMember = 0;
        }
    
        virtual ~Parent() {}
    };
    
    class Child1 : Parent<Child1>
    {
      int childMember;
    
      friend class Parent<Child1>;
    };
    
    0 讨论(0)
提交回复
热议问题