initializing mutable class attributes

Dan Perl dperl at rogers.com
Thu Sep 2 11:05:28 EDT 2004


"Alex Martelli" <aleaxit at yahoo.com> wrote in message
news:1gjg9tm.14a3nqg36zs8fN%aleaxit at yahoo.com...
     ........
> Incidentally, FAR from your assertion that, in C++, "subclasses don't
> need to know anything about how the superclass is implemented", reality
> is just the other way 'round.  Subclasses have to be _intimately
> familiar_ with key aspects of superclasses' implementation -- not just
> the interface (which fully includes the "little detail" of whether a
> class has a default ctor or not!!!), but specifically _implementation_
> issues, such as what private member names the superclass uses for its
> own implementation purposes.  That's because C++ fatally tries to
> support encapsulation via _accessibility_, NOT through _visibility_.  If
> the subclass unwittingly tries using a member name which the superclass
> is already using privately, it just won't compile; if the superclass
> adds any private names to its implementation from one release to
> another, it will "break all user code" which quite correctly tried to
> use that name (and previously managed w/o problems!) for one of its
> members -- as you say.

No, Alex.  Data members in a C++ subclass cannot conflict with data members
in its superclass, public, protected, or private.  They are resolved by
their namespaces.  See an example:
    #include <iostream>

    class Class1 {
    public:
        void setM1(int arg) {m1=arg;}
        void getM1( ) {std::cout << "c1m1: " << m1 << std::endl;}
    private:
        int m1;
    };
    class Class2 : public Class1 {
    public:
        void setM1(int c1m1, int c2m1) {Class1::setM1(c1m1);    m1=c2m1;}
        void getM1( ) {Class1::getM1( );      std::cout << "c2m1: " << m1 <<
std::endl;}
    private:
        int m1;
    };
    int main(int argc, char **argv)
        {
        Class2 c2 = Class2( );
        c2.setM1(1, 9);
        c2.getM1( );
        }

> Here it is -- now feel free to damage yourself at will with your
> conviction that this (calling superclass ctors) "IS a case" where
> implicit is better.  I decided I can reuse this as a Cookbook recipe,
> after all!-)

I'll look at the metaclass example later.  Thanks.

Dan





More information about the Python-list mailing list