Reputation: 2605
Consider the Base
class, and the two Child
classes:
class Base
{
public:
~Base() = default;
virtual void mouseCallback() = 0; // this is overriden by the Childs!
void mouseCallback2() { std::cout << "mouseCallback2 OK" << std::endl; }//Not overriden
};
class Child1 : public Base
{
public:
~Child1() = default;
void mouseCallback() override;
};
class Child2 : public Base
{
public:
~Child2() = default;
void mouseCallback() override;
};
Where the implementation is:
void Child1::mouseCallback()
{
std::cout << "Child 1 OK" << std::endl;
}
void Child2::mouseCallback()
{
std::cout << "Child 2 OK" << std::endl;
}
I have my CameraVision
class:
class CameraVision
{
public:
// ...
void init();
static void callback(int event, int x, int y, int flags, void* userdata);
private:
Base* mBase; // A pointer to the Base class!
}
Which contains the init()
method as follows:
void CameraVision::init()
{
mBase = new Child1();
// Here I set the callback
cv::setMouseCallback("Title", callback, &mBase);
}
So that when the mouse has an event I have this, the overriden method crashes my application.
void CameraVision::callback(int event, int x, int y, int flags, void* userdata)
{
if (event == cv::EVENT_LBUTTONDOWN)
{
Base* tof = static_cast<Base*>(userdata);
tof->mouseCallback2(); // THIS WORKS!
// But this is what I need
tof->mouseCallback(); // ERROR!!!!!!
}
}
Why I can't use the mouseCallback()
using inheritance of Child1
?
I'm getting an error
:
Exception thrown at 0x000000013F391938 in Demo.exe: 0xC0000005: Access violation executing location 0x000000013F391938
I was expecting the output
:
mouseCallback2 OK
Child 1 OK
Upvotes: 0
Views: 68
Reputation: 651
mBase is type Base*, then you don't need to use &, simply
cv::setMouseCallback("Title", callback, mBase);
&mBase will give you a pointer to a pointer, so your static_cast doesn't give you back the original mBase pointer, but its address. Not sure how the first callback worked, both should result in UB.
Upvotes: 2