Skip to main content
GameDev.net gamedev.net
🔒 Locked

deriving Python classes from a C++ class

Started by Ezbez Jan 9, 2007 at 6:15 AM 4 replies 1k views
Original Post
Ezbez
Ezbez
I know that this is possible, and I can do this. What I'd like to know is whether C++ will call the Python derived class's function if you call a virtual function in C++? Here's my example:
//C++
class Base
{
    virtual void Run()
    {
     std::cout << "Base class.";
     }
}

//Python, assuming that I've got the C++ class 'into Python' with boost::Python already
class Derived(Base):
    Run():
         print "Derived."

Then let's say that I've got: Base* ptr = SomeFactoryFunction(); //<- returns an instance of Derived() ptr->Run() Would that call Base::Run() or Derived::Run()? Thanks in advanced.
mikeman
mikeman
It's all in the Boost.Python documentation: link. Scroll down to "Class Virtual Functions" and "Virtual Functions with Default Implementations".

Personally, I just use Pyste to generate automatically the Boost.Python code from header files.
Ezbez
Ezbez
Alright, I understand that I can make classes in Python that derive from C++, but I'm not sure whether virtual functions called in C++ would use the derived class's function instead of the virtual function. That is, in my example, would it print 'Base' or 'Derived'?
mikeman
mikeman
That's the question you asked the first time, before I gave you link. Of course it will print "Derived", as expected. That's the whole point of these 2 paragraphs in the link.
Ezbez
Ezbez
Quote:
Original post by mikeman
That's the question you asked the first time, before I gave you link. Of course it will print "Derived", as expected. That's the whole point of these 2 paragraphs in the link.


I know it's the same, I was clarifying since I didn't see the answer in your link or post.

But, thanks for the answer and sorry for the confusion. I find this pretty mind-boggling for some reason. Run-time made classes being used in a language that only has classes made at compile-time seems very difficult to me, so I just had to check.
Vorpy
Vorpy
I think the "trick" is that the hooks for python objects to override C++ base class methods are created at compile time. Boost creates a derived class that contains a pointer to the python object and overrides all the virtual methods to check if the python object implements them. It's adding a layer of python style polymorphism on top of C++'s less flexible polymorphism.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.