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
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
}