Pointer-to-member function of derived class

  • Thread starter Rich Talbot-Watkins
  • Start date
R

Rich Talbot-Watkins

Hi all,

Thought I'd call on the experts to see if there's a solution to my problem -
it's best explained by way of an example. Consider the following code
extract:

//////////////////////////////////////////////////////////////

class CBaseClass;
struct BEHAVIOUR_TABLE
{
bool (CBaseClass::*m_pmfnHandler)();
int m_iWhatever;
};

class CBaseClass
{
public:
bool StandardWait();
};

class CDerivedClass : public CBaseClass
{
public:
static BEHAVIOUR_TABLE m_gastTable[];

bool SpecialisedPatrol();
bool SpecialisedAttack();
};

BEHAVIOUR_TABLE CDerivedClass::m_gastTable[] =
{
{ &StandardWait, 0 },
{ &SpecialisedPatrol, 1 },
{ &SpecialisedAttack, 2 }
};

// Dummy implementations of behaviour methods
bool CBaseClass::StandardWait() { return true; }
bool CDerivedClass::SpecialisedPatrol() { return true; }
bool CDerivedClass::SpecialisedAttack() { return true; }

//////////////////////////////////////////////////////////////

Effectively, I want to be able to declare a static array member for classes
derived from CBaseClass, containing pointers-to-member-functions for any
method of the form 'bool Method()' available to that derived class. This of
course could include superclass methods.

Compiling this produces the error:

a value of type "bool (CDerivedClass::*)()" cannot be used to initialize an
entity of type "bool (CBaseClass::*)()"
{ &SpecialisedPatrol, 1 }
^

Fair enough - but my question is: IS there a way of achieving this, given
the relationship between the two classes?

TIA,
Rich
 
A

Andrey Tarasevich

Rich said:
Compiling this produces the error:

a value of type "bool (CDerivedClass::*)()" cannot be used to initialize an
entity of type "bool (CBaseClass::*)()"
{ &SpecialisedPatrol, 1 }
^

Fair enough - but my question is: IS there a way of achieving this, given
the relationship between the two classes?
...

You have to use 'static_cast' explicitly in this case

BEHAVIOUR_TABLE CDerivedClass::m_gastTable[] =
{
{ &StandardWait, 0 },
{ static_cast<bool (CBaseClass::*)()>(&SpecialisedPatrol), 1 },
{ static_cast<bool (CBaseClass::*)()>(&SpecialisedAttack), 2 }
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top