473,837 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why can derived member function not access protected member of a baseclass object?

If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.

Can someone explain why this is? I suspect there is a good reason and
I am just having a slow day to not come up with it myself.

Bob
Sep 25 '08 #1
10 4123
Here is a sample program to show what I mean:

// Base.h
#ifndef Base_incl
#define Base_incl

class Derived; // forward declaration - required because Method2()
// of the Base class references the Derived class
class Base
{
public:
Base(); // constructor

virtual void Method1(Base &);
virtual void Method2(Base &);
virtual void Method3(Derived &); //it is unusual to have a
// derived class object as a parameter for a base
// class method, but as you see, it can be done.
protected:
int mBase;
};

#endif

// Derived.h
#ifndef Derived_incl
#define Derived_incl

#include "Base.h"

class Derived: public Base
{
public:
Derived(); // constructor

virtual void Method2(Base &); // this method
// overrides Base class Method2()
virtual void Method4(Base &); // a new method
// which is not defined for the Base class

private:
int mDerived;
};

#endif

// Base.cpp
#include "Base.h"
#include "Derived.h"

#include <iostream>
using std::cout;
using std::endl;

Base::Base()
{
this->mBase = 2;
}

void Base::Method1(B ase & B_Param)
{
cout << (B_Param.mBase) * (this->mBase) << endl;
}

void Base::Method2(B ase & B_Param)
{
cout << this->mBase << endl;
}

void Base::Method3(D erived & D_Param)
{
Base & BRef = static_cast<Bas e &>(D_Param); // This cast creates
// a Base class reference to the D_Param object.
cout << BRef.mBase << endl;
}

//Derived.cpp
#include "Derived.h"
#include <iostream>
using std::cout;
using std::endl;

Derived::Derive d()
{
this->mBase = 3;
this->mDerived = 5;
}

void Derived::Method 2(Base & B_Param)
{
cout << this->mDerived << endl;
}

void Derived::Method 4(Base & B_Param)
{
Derived * DPtr = dynamic_cast <Derived *(&B_Param); // this cast
// creates a Derived class pointer to B_Param, if and only if,
// B_Param actually is Derived class object, otherwise the
// pointer will be set to 0

if (DPtr != 0) // if B_Param is actually a Derived class object
cout << DPtr->mDerived << endl;
else
cout << B_Param.mBase << endl;
}

If I compile Derived.cpp I get the following errors:

1>c:\documents and settings\blange la\desktop\poly morphismtest
\derived.cpp(27 ) : error C2248: 'Base::mBase' : cannot access
protected member declared in class 'Base'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(17) : see declaration of 'Base::mBase'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(7) : see declaration of 'Base'

Sep 25 '08 #2
Sorry, it is the line:

cout << B_Param.mBase << endl;

in the member function below that causes the errors.

void Derived::Method 4(Base & B_Param)
{
Derived * DPtr = dynamic_cast <Derived *(&B_Param); // this
cast
// creates a Derived class pointer to B_Param, if and
only if,
// B_Param actually is Derived class object, otherwise
the
// pointer will be set to 0

if (DPtr != 0) // if B_Param is actually a Derived class
object
cout << DPtr->mDerived << endl;
else
cout << B_Param.mBase << endl;
}
Sep 25 '08 #3
blangela wrote:
If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.

Can someone explain why this is? I suspect there is a good reason and
I am just having a slow day to not come up with it myself.
Isn't this in the FAQ? It should be.

In short, the reason is to prevent access to members of a different type
(across the hierarchy). If D1 and D2 derive from B, an instance of D1
is not allowed to access any non-public members of D2 (unless they are
friends, of course). When you pass a reference to B to a member
function of D1, the access to members of that class is blocked because
it *can* be a subobject of a D2 object, and not necessarily of another
D1. Need an example? Look in the archives, we had that topic discussed
several times over the past years.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 25 '08 #4
On Sep 25, 12:55*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
blangela wrote:
If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.
Can someone explain why this is? *I suspect there is a good reason and
I am just having a slow day to not come up with it myself.

Isn't this in the FAQ? *It should be.

In short, the reason is to prevent access to members of a different type
(across the hierarchy). *If D1 and D2 derive from B, an instance of D1
is not allowed to access any non-public members of D2 (unless they are
friends, of course). *When you pass a reference to B to a member
function of D1, the access to members of that class is blocked because
it *can* be a subobject of a D2 object, and not necessarily of another
D1. *Need an example? *Look in the archives, we had that topic discussed
several times over the past years.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Even with the example you supply, what would be the harm of allowing
access to a member ( a member that was declared in the B class in your
example above) that we know must exist, no matter what subclass the
object actually belongs to (D1, D2, a subclass of D2, etc.)?

Sep 25 '08 #5
On Sep 25, 1:25*pm, blangela <Bob_Langel...@ telus.netwrote:
On Sep 25, 12:55*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:


blangela wrote:
If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.
Can someone explain why this is? *I suspect there is a good reason and
I am just having a slow day to not come up with it myself.
Isn't this in the FAQ? *It should be.
In short, the reason is to prevent access to members of a different type
(across the hierarchy). *If D1 and D2 derive from B, an instance of D1
is not allowed to access any non-public members of D2 (unless they are
friends, of course). *When you pass a reference to B to a member
function of D1, the access to members of that class is blocked because
it *can* be a subobject of a D2 object, and not necessarily of another
D1. *Need an example? *Look in the archives, we had that topic discussed
several times over the past years.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Even with the example you supply, what would be the harm of allowing
access to a member ( a member that was declared in the B class in your
example above) that we know must exist, no matter what subclass the
object actually belongs to (D1, D2, a subclass of D2, etc.)?- Hide quotedtext -

- Show quoted text -
Also, I changed the member function to:

void Derived::Method 4(Base & B_Param)
{
Derived * DPtr = dynamic_cast <Derived *(&B_Param); // this cast
// creates a Derived class pointer to B_Param, if and only if,
// B_Param actually is Derived class object, otherwise the
// pointer will be set to 0

if (DPtr != 0) // if B_Param is actually a Derived class object
cout << DPtr->mDerived << endl;
else
{
Base B_obj = B_Param;
cout << B_obj.mBase << endl;
}
}

And I still have the same errors:

1>c:\documents and settings\blange la\desktop\poly morphismtest
\derived.cpp(29 ) : error C2248: 'Base::mBase' : cannot access
protected member declared in class 'Base'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(17) : see declaration of 'Base::mBase'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(7) : see declaration of 'Base'

I would have thought that B_obj can only be a Base object now (and not
some subclass of Base), that it would now be allowed?
Sep 25 '08 #6
blangela wrote:
If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.

Can someone explain why this is? I suspect there is a good reason and
I am just having a slow day to not come up with it myself.

Bob
I know this is a C++ group and I hope I won't offend anyone by saying unlike in
C++ this kind of access is perfectly allowed in Java.
Sep 25 '08 #7
news.aioe.org wrote:
blangela wrote:
>If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.

Can someone explain why this is? I suspect there is a good reason and
I am just having a slow day to not come up with it myself.
I know this is a C++ group and I hope I won't offend anyone by saying
unlike in C++ this kind of access is perfectly allowed in Java.
Er... You sure about that? Is it possible that you just tried a toy
example with two classes in the same (e.g. top-level) package, and
forgot that "protected" in Java grants access to all classes in the same
package?
Sep 25 '08 #8
Jeff Schwab wrote:
news.aioe.org wrote:
>blangela wrote:
>>If I pass a base class object by reference (likely does not make a
difference here that it is passed by reference) as a parameter to a
derived class member function, the member function is not allowed to
access the protected data members of the base object. This surprises
me.

Can someone explain why this is? I suspect there is a good reason and
I am just having a slow day to not come up with it myself.
>I know this is a C++ group and I hope I won't offend anyone by saying
unlike in C++ this kind of access is perfectly allowed in Java.

Er... You sure about that? Is it possible that you just tried a toy
example with two classes in the same (e.g. top-level) package, and
forgot that "protected" in Java grants access to all classes in the same
package?
Yikes, I am embarrassed. That is exactly what I did! So it is consistent
between the two languages. When I moved the base class to a different package,
compiler throws an error:
x has protected access in package1.Base

Thanks for pointing out my mistake.
Sep 25 '08 #9
blangela wrote:
[..]
Also, I changed the member function to:

void Derived::Method 4(Base & B_Param)
{
Derived * DPtr = dynamic_cast <Derived *(&B_Param); // this cast
// creates a Derived class pointer to B_Param, if and only if,
// B_Param actually is Derived class object, otherwise the
// pointer will be set to 0

if (DPtr != 0) // if B_Param is actually a Derived class object
cout << DPtr->mDerived << endl;
else
{
Base B_obj = B_Param;
cout << B_obj.mBase << endl;
}
}

And I still have the same errors:

1>c:\documents and settings\blange la\desktop\poly morphismtest
\derived.cpp(29 ) : error C2248: 'Base::mBase' : cannot access
protected member declared in class 'Base'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(17) : see declaration of 'Base::mBase'
1 c:\documents and settings\blange la\desktop\poly morphismtest
\base.h(7) : see declaration of 'Base'

I would have thought that B_obj can only be a Base object now (and not
some subclass of Base), that it would now be allowed?
You changes the run-time behaviour of your program, but not the logic
for that particular statement. The rules of the language do not depend
on the run-time behaviour. The compiler is not going to verify the
run-time conditions when it checks the semantics of an expression.
Access is prohibited, period. It does not matter whether the *actual*
type of the super-object is the same or not because in general it isn't.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 26 '08 #10

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

Similar topics

5
1972
by: Andy Lomax | last post by:
Can anyone tell me why the code below doesn't compile? The code has a simple hierarchy of publically-derived classes: A -> B -> C. A declares a protected member 'foo'. C declares an object of type B, and attempts to access B.foo, which results in a compiler error: test.cpp: In member function `void C::test()': test.cpp:5: error: `int A::foo' is protected test.cpp:15: error: within this context
3
11834
by: Kirk Marple | last post by:
Just want to see if this is 'by design' or a bug... I have a common List<T> defined in a base class, and the base class has a static property to expose this list. I wanted the derived class to add items to this list, but have the base class hold the data and expose the property. Problem is, however, that the derived class' static constructor doesn't get called when DerivedClass.MyList is accessed, so the list has no members. If
2
1754
by: Joe HM | last post by:
Hello - I have a function in a base class that I want to use the shadow'ed member variable of the derived class. Here is the code ... Public Class cCaptureBase Protected Const cDummy As String = "Base" Overridable Sub print() Console.WriteLine(cDummy)
2
2643
by: Jessica | last post by:
I have a base class and a derived class, but I am getting errors when I try to access functions of the derived class. Simplified version of my code is as follows: //////////////// // test2.hh class BaseClass {
10
2531
by: benliu | last post by:
Is there an easy/special way to turn a base object into a derived object? So for example, given the following: class MyString : String { .... }
15
3090
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
3190
by: Dmitry | last post by:
Hi all, Consider the following code: class A { public: A() {} void DoMethod() { (this->*m_pMethod)(); } protected: virtual void MethodA() { ... }
6
8167
by: Bhawna | last post by:
I am into c++ code maintenance for last 3-4 years but recently I am put into design phase of a new project. Being a small comapany I dont have enough guidance from seniors. Currently I am into a situation where I am implementing base class functions by including a pointer to subclass member in base class. Reason being functionality is common for subclasses but the members are common within subclass only (static member of subclass) but...
3
1983
by: Edan | last post by:
I have a base class with protected members (`Base`). The function `MakeBase()` is a member function of another class, that returns a `Base` object initialized with private members of this class. Now the thing is, I want to extend the functionality of `Base` class. I do that by inheriting `Base` class by `Derived`, but then I can't use `MakeBase()` function. It all makes sense to me, but I don't seem to find an appropriate solution. Since I...
0
10874
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10566
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10271
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9398
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
7806
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
7000
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();...
0
5668
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4474
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
3
3124
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.