473,396 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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\nCDerived=%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 1498
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\nCDerived=%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.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - 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\nCDerived=%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\nCDerived=%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.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - 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\nCDerived=%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\nCDerived=%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\nCDerived=%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<CDerived*>(p_base); //
blasphemy!
p_semi_derived->x = 777;
}
};

void main ()
{
CBase obj_A;
CDerived obj_B;

printf ("CBase=%d\nCDerived=%d\n", static_cast<int>(obj_A),
static_cast<int>(obj_B));
obj_B.mymethod (&obj_A);
printf ("CBase=%d\nCDerived=%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\nCDerived=%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
Matthias Käppler wrote:
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.


It doesn't? Well, I think it really does: the replacement headers were
a nice idea which did not work out in practise. The reality is that
the C++ library implementer has no control over the ".h" versions but
is required to make sure that certain definitions from these headers
are made in namespace 'std'. The only available approach short of
keeping both versions in sync (which is not viable at all) is
something like this:

| // <cstdio>
| namespace std {
| #include "/usr/include/stdio.h"
| }

| // <stdio.h>
| #include <cstdio>
| using std::printf;
| // ...

(assuming the C version can be included from the file
/usr/include/stdio.h). However, this does not work because there are
loads of things defined in the standard C headers which are unknown
to either the C or the C++ standard and which other headers, e.g.
<unistd.h> rely upon being available in the global namespace.

The intention of putting away the declarations of the C library into
namespace 'std' was all noble - but it simply is not workable under
realistic conditions. Effectively, most implementations actually use
an approach like this:

| // <cfile>
| #include <stdio.h>
| namespace std {
| using ::printf;
| // ...
| }

.... and leave <stdio.h> unchanged (well, not really: it is still
necessary to add a few overloads to some of the headers e.g. for
const correctness but these declarations can easily be bolted on).
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.
Yup, I know. Actually, I have spread this bad recommendation myself
in the past. At this time I was convinced that I can implement the C++
headers in a conforming way - and I can, as long as you don't want to
include any non-standard headers like <unistd.h>, too (well, actually,
<ctime> really gave me a headache when trying to encapsulate glibc's
<time.h> for some reason). Since the non-standard headers are
generally necessary in real live in some translation units, you can
only implement conforming C++ <c...> headers if you also have
control over the ".h" headers or at least their contents. I'm not
aware of any C++ library vendor who really has.
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.
*/


I know that not all C++ library implementations are able to tag
all C definitions into namespace 'std': that's an easy one for
someone who has implemented most of the standard C++ library and
whose implementation does not do it for practical reasons. I'm
sure that my implementation is not the only one. Actually, there
is an open issue concerning this exact stuff (see
<http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#456>).

Although I recommended differently in the past, I recommend that
you use the ".h" version for the reasons given before.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting

Jul 22 '05 #11
I wasn't aware of this problem. Thanks.

Dietmar Kuehl wrote:
Matthias Käppler wrote:
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.


It doesn't? Well, I think it really does: the replacement headers were
a nice idea which did not work out in practise. The reality is that
the C++ library implementer has no control over the ".h" versions but
is required to make sure that certain definitions from these headers
are made in namespace 'std'. The only available approach short of
keeping both versions in sync (which is not viable at all) is
something like this:

| // <cstdio>
| namespace std {
| #include "/usr/include/stdio.h"
| }

| // <stdio.h>
| #include <cstdio>
| using std::printf;
| // ...

(assuming the C version can be included from the file
/usr/include/stdio.h). However, this does not work because there are
loads of things defined in the standard C headers which are unknown
to either the C or the C++ standard and which other headers, e.g.
<unistd.h> rely upon being available in the global namespace.

The intention of putting away the declarations of the C library into
namespace 'std' was all noble - but it simply is not workable under
realistic conditions. Effectively, most implementations actually use
an approach like this:

| // <cfile>
| #include <stdio.h>
| namespace std {
| using ::printf;
| // ...
| }

... and leave <stdio.h> unchanged (well, not really: it is still
necessary to add a few overloads to some of the headers e.g. for
const correctness but these declarations can easily be bolted on).
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.


Yup, I know. Actually, I have spread this bad recommendation myself
in the past. At this time I was convinced that I can implement the C++
headers in a conforming way - and I can, as long as you don't want to
include any non-standard headers like <unistd.h>, too (well, actually,
<ctime> really gave me a headache when trying to encapsulate glibc's
<time.h> for some reason). Since the non-standard headers are
generally necessary in real live in some translation units, you can
only implement conforming C++ <c...> headers if you also have
control over the ".h" headers or at least their contents. I'm not
aware of any C++ library vendor who really has.
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.
*/


I know that not all C++ library implementations are able to tag
all C definitions into namespace 'std': that's an easy one for
someone who has implemented most of the standard C++ library and
whose implementation does not do it for practical reasons. I'm
sure that my implementation is not the only one. Actually, there
is an open issue concerning this exact stuff (see
<http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#456>).

Although I recommended differently in the past, I recommend that
you use the ".h" version for the reasons given before.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting


Jul 22 '05 #12
xxx wrote:
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.


A member function of a derived class has access to the protected members
of objects it knows to be derived. It does not have access to protected
members of sibling classes. I think this is a reasonable approach.
Otherwise, the protection would be rather thin: a could easily derive
from base and access protected members from static functions of his
derived class without ever even creating an object! This would be
practically useless. If you need to access base members of sibling
classes, you effectively need public access.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
Jul 22 '05 #13

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

Similar topics

0
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...
13
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...
13
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...
1
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...
4
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...
3
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 :...
3
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...
1
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...
12
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...

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.