So, this is the final nagging inheritance question I’ve had for a little bit so I wanted to go on ahead and ask. So I’ll give an example in PHP:
<?php
class Base
{
private $z = 4;
function GetPrivate()
{
echo $this->z;
}
}
class Derived extends Base
{
}
$b = new Base();
$d = new Derived();
$d->GetPrivate();
?>
Simple enough. When I have always read about inheritance, the explanation were simply just “you inherit the public and protected members” and that’s it. What I don’t get are a couple things about how the interpreter in this example figures what belongs to what.
For example, when create a derived class, I am able to use the public function “GetPrivate” of the Base get the base class’s private variables. However, the simple definition of inheritance doesn’t work with this to me. What I mean is, I inherit the GetPrivate method but am still have some sort of link to private variables just from that method which belonged to the base class (even though $this refers to the derived class object). I couldn’t create a new function in the Derived class to access those private variables.
Thus, does the interpreter keep tabs on what were the inherited functions from the base class and the possible links they hold to private members only available to that base class?
The interpreter (or compiler in other OOP language), check the access one step at a time.
When you call
$d->GetPrivate();, the interpreter check the context in this is main (public context as I assume that you are not in a related class toDrerivedorBase) andGetPrivate()is a public method. Thus,$d->GetPrivate();is allowed in this context so no error.In
GetPrivate(), the context is$dobject asBaseand the access tozis a private element of the current object ($d). Thus the access is valid.The concept that comes in to play here is ‘Data Hiding’ (access control) and ‘Encapsulation’ (combination of data and function).
Inheritance of to play only to allows
GetPrivate()ofBaseto be used as it belong to an object ofDerived.It is true that there is still a link to a private Data but that link is not a direct one. The importance is that the access happen as
Baseclass allowed.So to answer your question is:
YES! The interpreter keep tabs on what were the inherited functions from the base class and the possible links they hold to private members only available to that base class.
Hope this helps.