[C++-sig] Inheritance question

Koen Van Herck koen_van_herck at yahoo.com
Fri Feb 10 16:46:24 CET 2006


Stefan Seefeld wrote:
>
> Koen Van Herck wrote:
> > Stefan Seefeld wrote:
> >
> >>Koen Van Herck wrote:
>
> >>>    class_<Derived>("Derived")
> >>>        .def("g", &Derived::g)
> >>>    ;
> >>
> >>This should be class_<Derived, bases<Base> > ...
> >
> >
> > Doesn't work, because I have not exposed Base.
>
> Oh, sorry ! I hadn't realized that.
>
> > I do expose Base, using a BaseWrap class as follows:
> >
> > class BaseWrap: public Base, public wrapper<Base>
> > {
> > public:
> >     void f()
> >     {
> >         this->get_override("f")();
> >     }
> > };
>
> I'm not sure what you mean by 'expose', but you certainly didn't
> expose it to python that way. If you want to be able to dispatch
> to methods expecting a 'Base' from within python, python has to know
> the 'Base' type. Alternatively, you can write a little wrapper
> function with the right signature that downcasts for you:

With 'expose' I meant using the class from Python. I didn't show the module
definition,
which follows Boost.Python's tutorial for virtual functions:

BOOST_PYTHON_MODULE(inheritance)
{
    class_<BaseWrap, boost::noncopyable>("Base")
        .def("f", pure_virtual(&Base::f))
    ;

    class_<User>("User")
        .def("useBase", &User::useBase)
    ;
}

This allows me to write following Python code:

    class PyDerived(inheritance.Base):
        def f(self):
            print 'PyDerived.f'

    u = inheritance.User()
    d = PyDerived()
    u.useBase(d)

and this works fine.
I was looking for a way to do

    u = inheritance.User()
    d = inheritance.Derived()
    u.useBase(d)

with inheritance.Derived() being the C++ Derived class (or some wrapper of
it).

>
> void useBase(User & u, Derived & d) { u.useBase(d); }
>
> and then use that instead of the member pointer:
>
>   class_<User> user("User");
>   user.def("useBase", useBase);

I'll try this.
How should I use this if I have more than one Derived? Like this:

void useBase1(User & u, Derived1 & d) { u.useBase(d); }
void useBase2(User & u, Derived2 & d) { u.useBase(d); }

user.def("useBase", useBase1);
user.def("useBase", useBase2);

>
> HTH,
> 		Stefan
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig




More information about the Cplusplus-sig mailing list