Reputation: 271
I've got a virtual base class:
class H{
public:
H(); // the implementation is in .cpp file, so this is not pure virtual
virtual ~H();
//... // other members
};
and the derived class:
class Hm : public H{
public:
Hm(){ /*define constructor*/ }
...
void method1();
};
I export two classes to Python using Boost.Python. Next, suppose there is another class X that contains a variable of type H:
class X{
public:
X(){ /*define constructor*/ }
H h; // data member
//...
};
The class and the variable h are also exposed to Python. Now, in Python I can do this:
x = X() # construct the object x of type X
x.h = Hm() # assign the data member of type H to the object of type Hm
# no problem with that, because of the inheritance
Now, the problem is - how do i call method of the class Hm (method1) from x.h? The object x.h is of type H, which does not define method of derived class method1. So the call
x.h.method1()
gives the error
So, is there any way to do that? Or perhaps i need to change the design of classes. In the latter case, what would be the most optimal way for the type of utilization i'm trying to do in the above example?
Upvotes: 1
Views: 179
Reputation: 8484
The behavior you are experiencing here is called slicing. "Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
If you want to be able to call method1()
you need either:
Hm
as a member to class X
H*
as a member to class X
and add virtual or pure virtual method1()
to class H
Some ideas how to expose pointer to python: here and here
Upvotes: 2