By chance, I have discovered something new related to the protected keyword yesterday. I was very surprised because I had never seen such a behavior in C++ or Java. But maybe I had never tested it in the past ? Anyway, I think it's important enough to share it with you.
Private keyword
Just for reminding, a private member will be visible only in the container object (class or structure). However, you can write something like :
public class ClassWithPrivate
{
private int privateMember;
public void DoSomething(ClassWithPrivate c)
{
c.privateMember = 12;
}
}
Protected keyword
With the previous example shown, we can expect a similar behavior with the protected keyword as it is an "extended private". Indeed a protected member will be visible in the container object and also in all the derived class of this object. However, there is a limitation when working with other instances as shown below:
public class BaseClass
{
protected void DoSomething() { }
}
public class DerivedClass : BaseClass
{
public void OtherMethod()
{
this.DoSomething();
DerivedClass derived = new DerivedClass();
derived.DoSomething();
BaseClass baseClass = new DerivedClass();
baseClass.DoSomething();
}
}
Experts of all language, can you tell me if you have this limitation also in your language ?
Extra question : I don't really see why we have this compilation error. Why this limitation exist ? DO you have any idea or clue ?