473,738 Members | 4,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling protected base class function on other (same typed) object

Hi,

Can anyone explain to me why the below fails to compile - seeing
otherA->f(); as a call to a inaccessible function, while otherB->f();
is ok?

It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.

I wanted to implement a recursion down a tree (via parent/child base
class pointers) and keep the virtual functions protected - but this
behaviour seems to force me to make them public.

Any info would be very helpful.

Thanks

Rick
class A
{
protected:
virtual void f() const {};
};

class B : public A
{
protected:
virtual void f() const
{
A::f(); // OK

// OK
B * otherB = new B();
otherB->f();

// Not OK - f() protected....
A * otherA = new B();
otherA->f(); };
};

Feb 6 '07 #1
6 4136
Rick wrote:
Can anyone explain to me why the below fails to compile - seeing
otherA->f(); as a call to a inaccessible function, while otherB->f();
is ok?

It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.
Access to protected members is allowed only through the object of
the same type. It's a limitation imposed by the language.
I wanted to implement a recursion down a tree (via parent/child base
class pointers) and keep the virtual functions protected - but this
behaviour seems to force me to make them public.
Consider the Visitor pattern. Keep virtual functions private and
have a public non-virtual function in the base class which will call
your virtual function. Or, make the visiting type a friend and keep
everything private.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Feb 6 '07 #2
On Feb 6, 3:56 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Rick wrote:
Can anyone explain to me why the below fails to compile - seeing
otherA->f(); as a call to a inaccessible function, while otherB->f();
is ok?
It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.

Access to protected members is allowed only through the object of
the same type. It's a limitation imposed by the language.
I guess this is a static versus dynamic binding issue? The access
specifiers having to be checked at compile time...?
I wanted to implement a recursion down a tree (via parent/child base
class pointers) and keep the virtual functions protected - but this
behaviour seems to force me to make them public.

Consider the Visitor pattern. Keep virtual functions private and
have a public non-virtual function in the base class which will call
your virtual function. Or, make the visiting type a friend and keep
everything private.
Looks like a good solution.

Thanks for the advice.

Rick

Feb 6 '07 #3
Rick wrote:
On Feb 6, 3:56 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>Rick wrote:
>>Can anyone explain to me why the below fails to compile - seeing
otherA->f(); as a call to a inaccessible function, while
otherB->f(); is ok?
>>It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.

Access to protected members is allowed only through the object of
the same type. It's a limitation imposed by the language.
I guess this is a static versus dynamic binding issue? The access
specifiers having to be checked at compile time...?
I know that the rule of allowing access to protected functions only
through an object of the same type stems from the fact that you're
not supposed to be able to use it across a hierarchy. Example:

class A {
protected:
void foo();
};

class B : public A {
public:
void bar(B& b) {
b.foo(); // OK
}
};

class C : public A {
public:
void bar(A& a) {
a.foo(); // NOT OK! Line 42
}
};

int main() {
B b;
C c;
c.bar(b);
}

If a call on line 42 were allowed, then you could call a protected
member function for an object (b) which has no relation to you (C).
I am not sure why it is bad, nothing immediately comes to mind.

[..]

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Feb 7 '07 #4
* Victor Bazarov:
I am not sure why it is bad, nothing immediately comes to mind.
If it were allowed you could access any protected member of any class
simply by deriving from that class.

As it is, you need at least a cast when using the derive-from-it method.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 7 '07 #5
Rick wrote:
>>
It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.

Access to protected members is allowed only through the object of
the same type. It's a limitation imposed by the language.
I guess this is a static versus dynamic binding issue? The access
specifiers having to be checked at compile time...?
The "protected" keyword allows to access to base class members of own
object, not base class members of other objects. Other objects of the same
class is exception due to copy and assign wants the access, but the
protected access to members of other objects of the same class is better to
use only for copy and assign purpose.

If you want to access to protected for other objects, use "friend".

--
Maksim A. Polyanin

"In thi world of fairy tales rolls are liked olso"
/Gnume/
Feb 10 '07 #6

Grizlyk wrote:
>>>
It seems you can happily access protected functions of another (same
type) - but not via a base class pointer.... I've checked the FAQs,
Meyers etc but nothing obvious I can find explains it.

Access to protected members is allowed only through the object of
the same type. It's a limitation imposed by the language.
I guess this is a static versus dynamic binding issue? The access
specifiers having to be checked at compile time...?

The "protected" keyword allows to access to base class members of own
object, not base class members of other objects. Other objects of the same
class is exception due to copy and assign wants the access, but the
protected access to members of other objects of the same class is better
to use only for copy and assign purpose.

If you want to access to protected for other objects, use "friend".
I have recallected how can access to other object. In the case of two
non-inherited different classes we can declare one as frient to other

class B;
class A{ friend class B; int i; };

but derived from other (derived from from B) will lose friend acssess, so
friend is not inherited, and if we wants to get access to one from derived
from other, we need to declare the access interface in other (in B).

class B
{
protected:
int& i(A& a)const {return a.i;}
};

class derived_B: public B
{
protected:
print(cosnt int);

public:
print(A& a){print( i(a) );}
};

By analogy, we need to declare in base forwarding interface to access from
derived from base to other base

template<class T>
class A
{
//logical protected interface
protected:
T member;

//protected access interface
//to logical protected interface
protected:
T& get_member(A& a)const{return a.member;}
};

template<class T>
class B: public A<T>
{
public:

void test()
{
// Not OK - f() protected....
//A * otherA = new B();
//otherA->f(); };

A<T *otherA = new B;
T tmp( get_member(*oth erA) );
}
};

--
Maksim A. Polyanin

"In thi world of fairy tales rolls are liked olso"
/Gnume/
Feb 11 '07 #7

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

Similar topics

8
1625
by: Andreas Lagemann | last post by:
Hi, after browsing FAQ and archive for a while I decided that the following is a legal question. Consider this: Class Base { public: Base() {}
13
7733
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:
5
3432
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
12
5811
by: st_ev_fe | last post by:
I've noticed that when constructing a subclass, the base class get's it's contructors called. Is there some way to avoid this? The base class has one variable, which gets initialised to 0. The subclass's constructor sets this variable to a real value. So first the variable is set to 0, the variable is never used before it once again gets set to a real value. It's a waste. Any ideas anyone?
11
3842
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...
12
1984
by: Peter Cranz | last post by:
hello, I've got the following problem: I have a construct similar like this: namespace A { class X {
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
6
4599
by: Me | last post by:
I need to be able to acces non-virtual members of sublcasses via a base class pointer...and without the need for an explicit type cast. I thought a pure virtual getPtr() that acts as a type cast would solve the problem, but it appears not to. I need this functionality to make object serialization a reality. Having to explicitly cast each deserialized object to its original type defeats the purpose of my serializing the blasted things in...
0
8969
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
8788
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,...
0
9476
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
9335
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
9208
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...
1
6751
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
4570
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...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2193
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.