Function pointers to member functions of a parent class
c++, function-pointers
Solution
A `void (Parent::*)()` takes an object of type Parent. The function `Child::afunc` requires an object of type Child. Converting the pointer to `void (Parent::*)()` would therefore allow for an invalid call.
Member function pointers can't really be used to implement polymorphism. The traditional way to implement polymorphism without using virtual is to use regular function pointers:
struct MyBaseClass
{
void (*function)(MyBaseClass* this_pointer);
};
Problem
I have been trying to understand function pointers in C++ so that I can successfully use them in one of my projects. I am running into a logic problem though. Say we have two classes: a parent class and a child class which inherits the parent class. ``` class Parent{ ...other stuff void (Parent::*ptr2func) (); ...other stuff }; ``` Then we have a child class: ``` class Child : public Parent{ ...other stuff void afunc(); ...other stuff }; ``` I wanted to connect the pointer of the parent class to the `afunc()` function of the child class. In the constructor of the child class is where I tried to do it like so: ``` Child::Child() { ptr2func = &Child::afunc; } ``` This returned an expected error: cannot convert `void (Child::*)()` to `void (Parent::*)()` in assignment. I was afraid that such a thing would happen. But how do I get over this? Can't I link a function pointer to a member function of a parent class to a member function of the child class? As you can understand I am trying to achieve polymorphism through function pointers just for experimenting and without using virtual functions. I was lead to believe that this is possible. What is my mistake? Or is it just not possible?