2

According to this post the following code below should compile, while it does not.

class Base
    protected m_x as integer
end class

class Derived1
    inherits Base
    public sub Foo(other as Base)
        other.m_x = 2
    end sub
end class

class Derived2
    inherits Base
end class

What could be the problem with it? I just made a new VB.NET console project and copy-pasted the code.

The error message I get is: 'SampleProject.Base.m_x' is not accessible in this context because it is 'Protected', and I have checked on different .NET framework versions (2.0, 3.0 and 3.5).

Community
  • 1
  • 1
Mikhail G
  • 311
  • 3
  • 9

3 Answers3

3

Protected members are only accessible from derived classes via MyBase.m_x (base in C#). You could write:

public sub Foo(other as Base)
    MyBase.m_x = 2
end sub

The reason why other.m_x = 2 does not compile is, because other is not(or must not necessarily be) the base class' instance of the current instance of Derived1. It could be any instance of Base because it is a parameter value.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

You can access the inherited variable, not the one from an instance of the base class.

class Base
    protected m_x as integer
end class

class Derived1
    inherits Base
    public sub Foo(other as Base)
        MyBase.m_x = 2 ' OK - Access inherited member
        other.m_x = 2 ' NOT OK - attempt to access a protected field from another instance
    end sub
end class
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • That is technically not correct. If both were of the type `Derived1`, you could access the protected member of both. The problem is that he is using the base type which is not legal (because `other` could be something like `Derived42` which has no relationship to `Derived1`). – Justin Niessner Nov 29 '10 at 14:06
  • @Justin - clarified that I am talking about an instance of the base class. – Oded Nov 29 '10 at 14:07
0

A key aspect of protected members is that a class can effectively seal off inherited protected members from access by any classes other than its ancestors (it would be nice if a class could both override a parent's method/property and also block child classes from accessing it, but so far as I can tell there's no way of doing that without adding an extra layer of hierarchy). For example, a class which happens to support cloning, but might be a useful base class for classes which would not, could have a Protected "Clone" method. Subclasses which don't support cloning could prevent their own subclasses from calling Clone by creating a dummy nested class called "Clone" which would shadow the parent Clone method.

If objects could access protected members elsewhere in the inheritance chain, this aspect of "protected" would no longer be applicable.

supercat
  • 77,689
  • 9
  • 166
  • 211