In C++
If we have BaseClass, ChildClass, and GrandchildClass. Where ChildClass inherits from BaseClass, and GrandchildClass inherits from ChildClass. There is also a StrangerClass unrelated to these types.
class ChildClass : public BaseClass
All scopes are aware ChildClass inherits from BaseClass, this includes StrangerClass.
class ChildClass : private BaseClass
Only ChildClass is aware ChildClass inherits from BaseClass… this includes GrandchildClass, if it were to inherit from ChildClass. GrandchildClass would not know that it is a BaseClass. StrangerClass knows nothing of ChildClass being a BaseClass.
class ChildClass : protected BaseClass
ChildClass and classes that inherit from it, like GrandchildClass, are aware they’re a BaseClass. But any other class is not aware, like StrangerClass, is unaware.
They aren’t… you need to be aware of the “Stranger” types.
Access modifiers don’t just pertain to the class inheritance chain. It pertains to all access, including access from types unrelated to the inheritance chain.
REMEMBER, Object-Oriented design isn’t just about inheritance. There’s 4 major principles:
Inheritance - a type can take on the functionality of an existing type
Encapsulation - a type can protect its members from direct access (public/private/protected)
Polymorphism - an object can be treated like another type if it’s related
Abstraction - data abstraction is the idea that through the use of the interface (methods of a type), the underlying data can be ignored, and there for abstracted. May you have a List that underneath is a Linked-List of items, or an array of items… they both act like Lists and have members like Lists… hence the IList type.
These all inter relate, so encapsulation (your access modifiers) don’t just deal with inheritance. They deal with it all.
A public member is how things act with your type.
A private members is things that are encapsulated away.
A protected members is a weird in between where you’ve abstracted data over a series of inherited types, but still need it encapsulated from other types.
Personally, I almost NEVER have a protected field. Only protected methods.
With that said, I use a limited amount of inheritance, and prefer a composition design through interfaces.
And always remember when discussing types, it’s best to think of them in the ‘is a’ relation.
ChildClass is a BaseClass.
This is what inheritance is saying…
Dog inherits from Mammal. Dog is a Mammal.