polymorphism and protected help

Discussion in 'C++' started by xxx, Dec 1, 2004.

  1. xxx

    xxx Guest

    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.
     
    xxx, Dec 1, 2004
    #1
    1. Advertising

  2. 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:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Dec 1, 2004
    #2
    1. Advertising

  3. xxx

    Rolf Magnus Guest

    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";


    > }
     
    Rolf Magnus, Dec 1, 2004
    #3
  4. > #include <stdio.h>

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

    Just curious.

    Cheers,
    Matthias
     
    Matthias =?ISO-8859-1?Q?K=E4ppler?=, Dec 1, 2004
    #4
  5. 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:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Dec 1, 2004
    #5
  6. xxx

    Ricky Corsi Guest

    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";
    >
    >
    >
    >> }

    >
    >
     
    Ricky Corsi, Dec 1, 2004
    #6
  7. xxx

    Rolf Magnus Guest

    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.
     
    Rolf Magnus, Dec 1, 2004
    #7
  8. 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
     
    Matthias =?ISO-8859-1?Q?K=E4ppler?=, Dec 1, 2004
    #8
  9. xxx

    xxx Guest

    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!
     
    xxx, Dec 1, 2004
    #9
  10. xxx

    Ricky Corsi Guest

    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.
    >
     
    Ricky Corsi, Dec 2, 2004
    #10
  11. 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:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Dec 2, 2004
    #11
  12. 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:> <http://www.dietmar-kuehl.de/>
    > <http://www.contendix.com> - Software Development & Consulting
     
    Matthias =?ISO-8859-1?Q?K=E4ppler?=, Dec 2, 2004
    #12
  13. 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:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Dec 3, 2004
    #13
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andreas Klemt
    Replies:
    2
    Views:
    569
    Andreas Klemt
    Jul 5, 2003
  2. Fao
    Replies:
    13
    Views:
    442
    osmium
    May 2, 2006
  3. Krivenok Dmitry
    Replies:
    13
    Views:
    1,452
    Axter
    Jun 1, 2006
  4. TimeHorse
    Replies:
    0
    Views:
    325
    TimeHorse
    Aug 9, 2007
  5. jungleman
    Replies:
    1
    Views:
    792
    James Kanze
    Aug 23, 2010
Loading...

Share This Page