I have a class named Reciever
that has a function called recieve(const Event *)
, where Event
inherits from BaseEvent
. I want to create a bind to a specific instance of that class. The instance is called rec
. To do this I use:
void(Reciever::*func)(const Event *) = &Reciever::recieve;
auto recievePtr = std::bind(func, &rec, std::placeholders::_1);
However, when I try to store this in a vector, I have to specify an std::function
that takes a BaseEvent
as the input, not an Event
, like so:
std::vector<std::function<void(const BaseEvent*)>>
How can I cast recievePtr
so I can store it properly in the vector? Is this even possible? The issue with using a function pointer to a BaseEvent
is that the Reciever
can have multiple recieve()
methods with different derived classes all based on BaseEvent
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
Base class object will call base class function and derived class object will call derived class function.
38. What happens if the base and derived class contains definition of a function with same prototype? A. Compiler reports an error on compilation.
You cannot call a derived virtual method from inside of a base class constructor/destructor. The VMT does not contain a pointer to the derived class method table at those stages. Save this answer. Show activity on this post.
You can try something along the following. This compiled and ran fine on my machine. Visual Studio targeting platform toolset v120.
Reciever rec;
std::vector<std::function<void(const BaseEvent*)>> vector;
vector.push_back(
[&rec](const BaseEvent* event)
{
rec.recieve(static_cast<const Event*>(event));
});
vector.push_back(
[&rec](const BaseEvent* event)
{
rec.recieve(static_cast<const EventD*>(event));
});
const BaseEvent* e = new Event();
const BaseEvent* d = new EventD();
vector[0](e);
vector[1](d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With