Access child members within parent class, C++

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

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

    template
    class Parent
    {
        void DoSomething()
        {
            // This is what I need
            T::childMember = 0;
        }
    
        virtual ~Parent() {}
    };
    
    class Child1 : Parent
    {
      int childMember;
    
      friend class Parent;
    };
    

提交回复
热议问题