Reputation: 445
This is a simplified example of a design problem.
I have the class Base
. It has a function pointer type and a protected variable of that function pointer type.
#ifndef BASE_H
#define BASE_H
class Base {
typedef void (Base::*FunctionPointer) ( void );
protected:
FunctionPointer pointer;
};
#endif /* BASE_H */
Then I have the class Derived
that inherits from Base
. This class wants to be able to set the inherited pointer
variable equal to addresses for it's own methods, not ones inherited or overridden from Base
.
#ifndef DERIVED_H
#define DERIVED_H
#include "Base.h"
class Derived : public Base{
public:
Derived()
{
pointer = &Derived::ProtectedMethod;
}
void ProtectedMethod()
{
}
};
#endif /* DERIVED_H */
The problem is that the type of function pointers (void (Base::*FunctionPointer) ( void )
and void (Derived::*FunctionPointer) ( void )
) are different.
In Short
Is there a way to have a pointer variable in a base class that can be assigned to derived classes methods (not overridden)?
Upvotes: 1
Views: 48
Reputation: 50540
I'm with @RSahu: it is not possible for they are unrelated types.
I'm adding this answer for the sake of curiosity.
You can do something similar with the CRTP idiom:
template<class D>
struct B {
using FnType = void(D::*)();
FnType ptr{nullptr};
};
struct D: B<D> {
D(): B{} {
ptr = &D::method;
}
void method() { }
};
This is not exactly what you asked for, but it is a viable solution at least.
Upvotes: 1
Reputation: 206567
Is there a way to have a pointer variable in a base class that can be assigned to derived classes methods (not overridden)?
No, you cannot do that. They are unrelated types.
Upvotes: 4