Access child members within parent class, C++

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

    Apparently you have some subset of derived classes which utilise childMember. For these classes you have some method "DoSomething()" which can be called. I guess for all other derived classes the method DoSomething() is not applicable. Why don't you create another abstraction level for this set of derived classes?

    class Parent
    {
        // no DoSomething()
    }
    
    class ChildMemberClasses : Parent
    {
        int childMember;
    
        void DoSomething()
        {
            // code that uses childMember
        }
    }
    
    class ChildWithChildMember : ChildMemberClasses
    {
        // other stuff
    }
    

    If DoSomething() has some meaning for classes without childMember, you can still define the it as virtual method in Parent. Like this:

    class Parent
    {
        virtual void DoSomething()
        {
            // code that does not use childMember
        }
    }
    
    class ChildMemberClasses : Parent
    {
        int childMember;
    
        void DoSomething()
        {
            // code that uses childMember
        }
    }
    
    class ChildWithChildMember : ChildMemberClasses
    {
        // other stuff
    }
    

提交回复
热议问题