473,729 Members | 2,141 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Protected Member

Hi All,

I have a small C#.NET program that is as follows:

using System;

class A
{
protected int x = 123;
}

class B : A
{
static void Main()
{
A a = new A();
B b = new B();

a.x = 10; // Compiling error here
b.x = 10;
}

}

Now I get a compiling error:
Cannot access protected member 'A.x' via a qualifier of type 'A'; the
qualifier must be of type 'B' (or derived from it)

I'm confused - Since "x" is defined in class "A", how come "a" which
is of class "A" cannot access "x" while "b" which is not of class "A"
can?

Thanks,
-Emily

Feb 15 '07 #1
16 3628

"Fir5tSight " <fi********@yah oo.comwrote in message
news:11******** **************@ m58g2000cwm.goo glegroups.com.. .
Hi All,

I have a small C#.NET program that is as follows:

using System;

class A
{
protected int x = 123;
}

class B : A
{
static void Main()
{
A a = new A();
B b = new B();

a.x = 10; // Compiling error here
b.x = 10;
}

}

Now I get a compiling error:
Cannot access protected member 'A.x' via a qualifier of type 'A'; the
qualifier must be of type 'B' (or derived from it)

I'm confused - Since "x" is defined in class "A", how come "a" which
is of class "A" cannot access "x" while "b" which is not of class "A"
can?

Thanks,
-Emily
Are you sure that you're not getting the error because you're attempting to
initialize a field in a class definition?
I.e. where you:

protected int x = 123;

?
What happens if you just

protected int x;

?
Feb 15 '07 #2
I am getting the error. I have to comment out the line of code:

//a.x = 10; // Compiling error here

in order for it to compile.

-Emily

Feb 15 '07 #3
I am getting the error. In order for it to compile successfully, I
must comment out the line of code:

//a.x = 10; // Compiling error here

My question is: Why does this line of code cause compiling error?

-Emily

Feb 15 '07 #4
Fir5tSight <fi********@yah oo.comwrote:

<snip>
Now I get a compiling error:
Cannot access protected member 'A.x' via a qualifier of type 'A'; the
qualifier must be of type 'B' (or derived from it)

I'm confused - Since "x" is defined in class "A", how come "a" which
is of class "A" cannot access "x" while "b" which is not of class "A"
can?
You only get access to the protected members of instances of your own
class, not to just any instance of the base class.

The C# spec puts it somewhat cryptically:

<quote>
When a protected instance member is accessed outside the program text
of the class in which it is declared, and when a protected internal
instance member is accessed outside the program text of the program in
which it is declared, the access is required to take place through an
instance of the derived class type in which the access occurs.
</quote>

Effectively, you're allowed to access things you've inherited yourself,
but you can't start stealing someone else's inheritance :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 15 '07 #5
"Fir5tSight " <fi********@yah oo.coma écrit dans le message de news:
11************* *********@m58g2 00...legr oups.com...

| class A
| {
| protected int x = 123;
| }
|
| class B : A
| {
| static void Main()
| {
| A a = new A();
| B b = new B();
|
| a.x = 10; // Compiling error here
| b.x = 10;
| }
|
| }
|
| Now I get a compiling error:
| Cannot access protected member 'A.x' via a qualifier of type 'A'; the
| qualifier must be of type 'B' (or derived from it)
|
| I'm confused - Since "x" is defined in class "A", how come "a" which
| is of class "A" cannot access "x" while "b" which is not of class "A"
| can?

First question: why are you holding an instance of A inside B ? An instance
of B *is* an instance of A already.

As others have said, even though B derives from A, protected members of A
are only available from *the same instance* of a derived class.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Feb 15 '07 #6
I don't know why one would hold an instance of A inside B. This is
sample code from Microsoft training class illustrating the use of
protected member.

It says b.x is valid while a.x is not valid and that's why I get
compiling error at a.x = 10;

Sorry, after all of you have tried to explain this to me, I still
don't understand. Why a.x is not valid, but b.x is valid?

I see that x is defined in A of which a is an instance.

-Emily

Feb 15 '07 #7
"Fir5tSight " <fi********@yah oo.coma écrit dans le message de news:
11************* ********@l53g20 00...legro ups.com...

|I don't know why one would hold an instance of A inside B. This is
| sample code from Microsoft training class illustrating the use of
| protected member.

In that case, the code is purely to demonstrate that it is only possible to
access protected members from the same instance of a given derived class as
opposed to from an instance of the derived class that contains an instance
of A.

| It says b.x is valid while a.x is not valid and that's why I get
| compiling error at a.x = 10;

And that is correct. a.x is not visible from an instance of B that
*contains* an instance of A.

| Sorry, after all of you have tried to explain this to me, I still
| don't understand. Why a.x is not valid, but b.x is valid?
|
| I see that x is defined in A of which a is an instance.

Correct again, but there is a difference which I shall try to explain inline
with your code.

class A
{
protected int x = 123;
}

x is s protected field in the class A. This means that any code inside the A
class can access x, as can any code inside a class derived from A.

class Test
{
static void Main()
{
A a = new A();

a.x = 10; // will not compile
}
}

This will fail because x is only visible inside instances of A or its
derivatives. Test does not derive from A, therefore it can't see x.

class B : A
{
public void AssignX()
{
x = 10; // this compiles
}
}

This will work because B derives from A and can see the protected field x.

class B : A
{
static void Main()
{
B b = new B();

b.x = 10; // this compiles
}
}

This works because code inside B can see anything inside any instance of B,
even the private and protected members like x.

class B : A
{
static void Main()
{
A a = new A();

a.x = 10; // will not compile
}
}

This, however, shows that although B derives from A, code inside the B class
cannot see private and protected members of A, because 'a' is not an
instance of B and therefore does not allow access to its private and
protected members.

Code inside derived classes can only see private and protected members of
other instances of that derived class, not instances of the base class. the
privilege of seeing members of the base class is only accorded to code
inside *the same instance* of the *derived* class.

Finally, you should note that the Main() method is marked as static and
therefore could not see *any* instance fields, only static fields. This is
why the example shows creating instances of A and B.

Does that help ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Feb 15 '07 #8

"Joanna Carter [TeamB]" <jo****@not.for .spamwrote in message
news:ug******** *****@TK2MSFTNG P02.phx.gbl...
"Fir5tSight " <fi********@yah oo.coma écrit dans le message de news:
11************* ********@l53g20 00...legro ups.com...

|I don't know why one would hold an instance of A inside B. This is
| sample code from Microsoft training class illustrating the use of
| protected member.

In that case, the code is purely to demonstrate that it is only possible
to
access protected members from the same instance of a given derived class
as
opposed to from an instance of the derived class that contains an
instance
of A.

| It says b.x is valid while a.x is not valid and that's why I get
| compiling error at a.x = 10;

And that is correct. a.x is not visible from an instance of B that
*contains* an instance of A.

| Sorry, after all of you have tried to explain this to me, I still
| don't understand. Why a.x is not valid, but b.x is valid?
|
| I see that x is defined in A of which a is an instance.

Correct again, but there is a difference which I shall try to explain
inline
with your code.

class A
{
protected int x = 123;
}

x is s protected field in the class A. This means that any code inside
the A
class can access x, as can any code inside a class derived from A.

class Test
{
static void Main()
{
A a = new A();

a.x = 10; // will not compile
}
}

This will fail because x is only visible inside instances of A or its
derivatives. Test does not derive from A, therefore it can't see x.

class B : A
{
public void AssignX()
{
x = 10; // this compiles
}
}

This will work because B derives from A and can see the protected field
x.

class B : A
{
static void Main()
{
B b = new B();

b.x = 10; // this compiles
}
}

This works because code inside B can see anything inside any instance of
B,
even the private and protected members like x.

class B : A
{
static void Main()
{
A a = new A();

a.x = 10; // will not compile
}
}

This, however, shows that although B derives from A, code inside the B
class
cannot see private and protected members of A, because 'a' is not an
instance of B and therefore does not allow access to its private and
protected members.

Code inside derived classes can only see private and protected members of
other instances of that derived class, not instances of the base class.
the
privilege of seeing members of the base class is only accorded to code
inside *the same instance* of the *derived* class.

Finally, you should note that the Main() method is marked as static and
therefore could not see *any* instance fields, only static fields. This
is
why the example shows creating instances of A and B.

Does that help ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer

So say I had a class called Customer that had a protected property called
PhoneNumber.

Then I had a class called CustomerList that was a List(Of Customer), I
could see the phone number, right? Because each item in the list is a
Customer?

But if i had a class called Product that instantiated a Customer inside it,
I could not see the PhoneNumber.

Is that right?

Robin S.
Feb 16 '07 #9
Joanna Carter [TeamB] <jo****@not.for .spamwrote:

<snip>
| I'm confused - Since "x" is defined in class "A", how come "a" which
| is of class "A" cannot access "x" while "b" which is not of class "A"
| can?

First question: why are you holding an instance of A inside B ? An instance
of B *is* an instance of A already.

As others have said, even though B derives from A, protected members of A
are only available from *the same instance* of a derived class.
No, that's not quite right. Code in B can access protected members of A
"through" any instance of B or a derived class. It doesn't have to be
any particular instance of B, and in particular it doesn't need to be
"this" during an instance method.

The important thing is that you're accessing the member through an
object known (at compile time) to be an instance of B, not just an
instance of A or some different derived class.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 16 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2309
by: Steven T. Hatton | last post by:
I find the surprising. If I derive Rectangle from Point, I can access the members of Point inherited by Rectangle _IF_ they are actually members of a Rectangle. If I have a member of type Point in Rectangle, the compiler tells me Point::x is protected. I would have expected Rectangle to see the protected members of any Point. Compiling the following code give me this error: g++ -o rectangle main.cc main.cc: In member function `size_t...
13
7732
by: Adam H. Peterson | last post by:
I just made an observation and I wondered if it's generally known (or if I'm missing something). My observation is that static protected members are essentially useless, only a hint to the user. They don't actually protect any encapsulation or anything, and for all the actual protection they offer, they might as well be public. For example: class B { protected:
11
3841
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
3
6721
by: Jordan Taylor | last post by:
I am confused about protected member functions and objects. Is there any particular advantage of declaring members protected?
14
2473
by: mlimber | last post by:
In an article on the safe bool idiom (http://www.artima.com/cppsource/safeboolP.html), Bjorn Karlsson gives the following code (slightly modified): class safe_bool_base { protected: typedef void (safe_bool_base::*bool_type)() const; void this_type_does_not_support_comparisons() const {} safe_bool_base() {}
2
1938
by: t | last post by:
Lippman's C++ Primer, 4th ed., p562, dicussion of protected members seems to be wrong, unless I am misinterpreting things. He says: "A derived class object may access the protected members of its base class only through a derived object. The derived class has no special access to the protected members of base type objects." He gives the following example: =========================================================
15
3086
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I met with a strange issue that derived class function can not access base class's protected member. Do you know why? Here is the error message and code. error C2248: 'base::~base' : cannot access protected member declared in
3
3184
by: Dmitry | last post by:
Hi all, Consider the following code: class A { public: A() {} void DoMethod() { (this->*m_pMethod)(); } protected: virtual void MethodA() { ... }
8
2594
by: Mayur H Chauhan | last post by:
All, For my knowledge, if I declare Class as follow, then it thows compilation error. Protected Class Book End Class Even same for...
0
8927
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8764
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9210
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8159
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6026
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3242
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2694
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2166
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.