473,785 Members | 2,411 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

polymorphism and protected help

xxx

I'm having a little trouble understanding why a derivative class cannot
access a protected member of the base class in the following code:
#include <stdio.h>

class CBase
{
protected:
int x;
public:
CBase () {x = 123;}
public:
operator int () {return x;}
};

class CDerived : public CBase
{
public:
CDerived ()
{
CBase* p = this;
p->x = 456; // error: cannot access protected member
}
};

void main ()
{
printf ("CBase=%d\nCDe rived=%d\n", CBase (), CDerived ());
}
I don't see why CDerived shouldn't be able to access the integer "x" in
CBase without having CBase to declare CDerived as a friend. Can someone
explain to me why this is? Thank you.
Jul 22 '05 #1
12 1529
xxx wrote:
class CBase
{
protected:
int x;
};

class CDerived : public CBase
{
public:
CDerived ()
{
CBase* p = this;
p->x = 456; // error: cannot access protected member
In this context the compiler does not know that 'p' is actually
of type 'CDerived'. Thus, it assumes that you are possibly
playing with the private parts of a sibling. I doubt that this
would be appreciated in real life and is consequently also not
allowed in C++. If I remember correctly, authors of other
languages have a different attitude towards this...

BTW: void main ()
The above declaration is illegal according to the C standard:
'main()' has to return an 'int'.
{
printf ("CBase=%d\nCDe rived=%d\n", CBase (), CDerived ());
}
Implicit conversions are not applied when passing arguments to
a variable parameter list.
I don't see why CDerived shouldn't be able to access the integer "x" in CBase without having CBase to declare CDerived as a friend. Can someone explain to me why this is? Thank you.


Actually, this question is also answered in the FAQ.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #2
xxx wrote:

I'm having a little trouble understanding why a derivative class cannot
access a protected member of the base class in the following code:
#include <stdio.h>

class CBase
{
protected:
int x;
public:
CBase () {x = 123;}
public:
operator int () {return x;}
};

class CDerived : public CBase
{
public:
CDerived ()
{
CBase* p = this;
p->x = 456; // error: cannot access protected member
Just write:
x = 456;
}
};

void main ()
main() must return int.
{
printf ("CBase=%d\nCDe rived=%d\n", CBase (), CDerived ());
You cannot pass objects through variable argument list, and the compiler
doesn't know that it has to use your operator int(), so you have to cast
your objects to int before giving them to printf:

printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(CBase ()),
static_cast<int >(CDerived ()));

Or just use cout (#include <iostream> at the top):

std::cout << "CBase=" << CBase() << "\nCDerived =" << CDerived() << "\n";

}


Jul 22 '05 #3
> #include <stdio.h>

I know that's legal, but shouldn't this rather be #include <cstdio> ?

Just curious.

Cheers,
Matthias

Jul 22 '05 #4
Matthias Käppler wrote:
#include <stdio.h>


I know that's legal, but shouldn't this rather be #include <cstdio> ?

Just curious.


Probably, <stdio.h> is the better alternative: the reality is that
effectively no C++ standard library declares the C functions in
namespace 'std' and then imports them in the ".h" header via using
directives. Typically, it is done the other way around, i.e. the
names are defined in the global namespace and then made available
in namespace 'std'. Unfortunately, this causes some potential errors
to go undetected, e.g.:

#include <cstdio>
int main() { printf("hello, world\n"); }

The above program will compile with several different C++ library
implementations - but not with a standard conforming one. As a
consequence, it is a safer approach to use <stdio.h> in the first
place because a program compiling with this header on either a
broken or conforming library implementation will also compile on
the other one (where I make, of course, certain assumption about
the broken implementations ...).
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #5
Rolf Magnus wrote:
xxx wrote:

I'm having a little trouble understanding why a derivative class cannot
access a protected member of the base class in the following code:
#include <stdio.h>

class CBase
{
protected:
int x;
public:
CBase () {x = 123;}
public:
operator int () {return x;}
};

class CDerived : public CBase
{
public:
CDerived ()
{
CBase* p = this;
p->x = 456; // error: cannot access protected member

Just write:
x = 456;

}
};

void main ()

main() must return int.

{
printf ("CBase=%d\nCDe rived=%d\n", CBase (), CDerived ());

You cannot pass objects through variable argument list, and the compiler
doesn't know that it has to use your operator int(), so you have to cast
your objects to int before giving them to printf:

printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(CBase ()),
static_cast<int >(CDerived ()));


Sorry, why do you say that the compiler is not able to implicitly
convert a classed passed as a parameter of a function??

I wrote this simple code and both compiles and works. Can you explain me
what you mean? thanks_ricky

#include <iostream>

using namespace std;

class Converse
{
public:
Converse(int init = 0) : x(init) {};
operator int () {return x;};

private:
int x;
};

int summa(int x, int y)
{
return x+y;
}
int main()
{
Converse c1(7);
int val = 3;
int result = summa(val, c1);

cout << result << endl; // this prints exactly 10

return 0;
}



Or just use cout (#include <iostream> at the top):

std::cout << "CBase=" << CBase() << "\nCDerived =" << CDerived() << "\n";
}


Jul 22 '05 #6
Ricky Corsi wrote:
You cannot pass objects through variable argument list, and the compiler
doesn't know that it has to use your operator int(), so you have to cast
your objects to int before giving them to printf:

printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(CBase ()),
static_cast<int >(CDerived ()));
Sorry, why do you say that the compiler is not able to implicitly
convert a classed passed as a parameter of a function??


I didn't say that. I said that it doesn't know which type a function expects
as part of a _variable_ argument list and therefore doesn't know it has to
convert the argument in the above code to int.
I wrote this simple code and both compiles and works.


That code doesn't use a variable argument list.

Jul 22 '05 #7
Dietmar Kuehl wrote:
The above program will compile with several different C++ library
implementations - but not with a standard conforming one.


That doesn't really make sense.
From what I know, the <cxyz> headers are the ISO-C++ counterparts to the
classic xyz.h headers and were introduced in the standardization process to
make clear which are C headers and which are not. It's actually highly
encouraged to use them whenever you want to include C headers.

This is directly copied from <cstdio>:

//
// ISO C++ 14882: 27.8.2 C Library files
//

/** @file cstdio
* This is a Standard C++ Library file. You should @c #include this file
* in your programs, rather than any of the "*.h" implementation files.
*
* This is the C++ version of the Standard C Library header @c stdio.h,
* and its contents are (mostly) the same as that header, but are all
* contained in the namespace @c std.
*/

Regards,
Matthias
Jul 22 '05 #8
xxx
The intention was to have access to CBase's protected member from CDerived
without having to write a bunch of public accessors in CBase--it would
defeat the purpose to be protected.

Based on the assumption that the compiler preserves the location of CBase in
CDerived:
#include <stdio.h>

class CBase
{
protected:
int x;
public:
CBase () {x = 123;}
public:
operator int () {return x;}
};

class CDerived : public CBase
{
public:
CDerived () {x = 456;}
public:
void mymethod (CBase* p_base)
{
// p->x = x * 666; // error: cannot access protected member

CDerived* p_semi_derived = static_cast<CDe rived*>(p_base) ; //
blasphemy!
p_semi_derived->x = 777;
}
};

void main ()
{
CBase obj_A;
CDerived obj_B;

printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(obj_A),
static_cast<int >(obj_B));
obj_B.mymethod (&obj_A);
printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(obj_A),
static_cast<int >(obj_B));
}
/*
output:

CBase=123
CDerived=456
CBase=777
CDerived=456
*/
But this will break between different implementations of compilers and
perhaps classes with different orderings of base classes--a.k.a. a hack job.

My intention was to have a base class with numerous protected data members
that only derived classes can access and modify. Some nodes of an AST parse
tree may need to modify other node attributes based on some type. I thought
it would be clear to make data members protected because I have multiple
parsers in the same project. If we take a look at "mymethod(. ..)" from the
above code, then it would represent some derivation of AST Node trying to
modify another derivation of AST Node. Using friends is quite painful the
same way as it is not safe to give away private access when not absolutely
necessary.

Has anyone any other ideas? (Please link me to a URL if there's something I
should read.) Much appreciated!
Jul 22 '05 #9
Rolf Magnus wrote:
Ricky Corsi wrote:

You cannot pass objects through variable argument list, and the compiler
doesn't know that it has to use your operator int(), so you have to cast
your objects to int before giving them to printf:

printf ("CBase=%d\nCDe rived=%d\n", static_cast<int >(CBase ()),
static_cast<int >(CDerived ()));
Sorry, why do you say that the compiler is not able to implicitly
convert a classed passed as a parameter of a function??

I didn't say that. I said that it doesn't know which type a function expects
as part of a _variable_ argument list and therefore doesn't know it has to
convert the argument in the above code to int.


Oh right, I see now what you mean. I didn't pay attention to the
function (printf) you were referring to...
thanks_ricky

I wrote this simple code and both compiles and works.

That code doesn't use a variable argument list.

Jul 22 '05 #10

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

Similar topics

0
1046
by: Ultra | last post by:
Hi Export, I want to write a class to deal with all db tier with different platform, but when I using a DbAdapter (superclass) pointer to point a OleDBAdapter (subclasse) instance, it said the selectCommand is protected. How can I do that polymorphism? below is my class: public class db {
13
3261
by: Fao | last post by:
Hello, I am having some problems with inheritance. The compiler does not not return any error messages, but when I execute the program, it only allows me to enter the number, but nothing else happend. I think the problem may be in my input function or in the main function. If anyone out there can help me it woul be greatly appreciated. Here is the code: #include <iostream>
13
2020
by: Jack | last post by:
I have a class called "Base". This class has a protected member variable "m_base" which can be retrieved using the public member function "GetBaseMember". "m_base" is initialized to "1" and is never changed. I have another class which is a subclass of the "Base" class called "Derived". This derived class has a member variable called "m_derived". "m_derived" is initialized to "2" and is never changed. I pass an array of "Base" classes...
1
1580
by: n355a | last post by:
hi everyone....if anyone has time... can anyone help me with virtual functions... I have class student, Graduate, Undergraduate. There's a printInfo() in each class, and the one in student is made pure virtual. I had to create a vector of students that had a combination of Graduates and Undergraduates in main. Then I had to pass the vector to a function. In that function theres a loop that goes through each students and prints their...
4
1845
by: maxgross | last post by:
Hi everyone, ive got a problem with polymorphism. When i compile the code an error occures: error: 'class QtElement' has no member named 'DisplayQtElement' I asked my friends and nobody could help me, all said it has to work. I work with wxWidgets 2.6.3 under Linux.
3
1866
by: lorenzon | last post by:
I've run into a problem in some code involving two class hierarchies that I can't figure out: I have an event hierachy topped with an interface, let's say- IEvent, EventA : IEvent, EventB : IEvent And some handlers-
3
1907
by: TamusJRoyce | last post by:
Hello. This is my first thread here. My problem has probably been came across by a lot of people, but tutorials and things I've seen don't address it (usually too basic). My problem is that I would like to use Abstraction for a "plug-in" like interface to classes. class ThreadHandle { /* stuff here not yet dealing with threads */
1
10102
weaknessforcats
by: weaknessforcats | last post by:
Introduction Polymorphism is the official term for Object-Oriented Programming (OOP). Polymorphism is implemented in C++ by virtual functions. This article uses a simple example hierarchy which you may have seen many times in one form or another. An analysis of this example produces several problems that are not obvious but which will seriously limit your ability to use hierarchies like the example in a real program. Then, the article...
12
2541
by: feel | last post by:
Hi,All I am sure it's an old question. But I just find a interesting design about this: Polymorphism without virtual function in a C++ class. My solution is for some special case, trust me, very special. 1 single root class tree 2 the leaf(lowest level) classes are sealed which means we should not inherite class from them. 3 PImpl idiom. There is only one data mumber in root class and there is no any other data mumber in child class and...
0
9646
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
9483
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
10346
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...
1
10096
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
9956
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
6742
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
5386
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
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.