Elan Hickler
Elan Hickler

Reputation: 1139

C++ assign member object function to class member function

Is there a way to use an = type assignment instead of this syntax:

void triggerAttack() { adsr.triggerAttack(); }

I was hoping to do something like:

void triggerAttack() = adsr.triggerAttack

std::function<void()> triggerAttack = adsr.triggerAttack

void(*triggerAttack)() = adsr.triggerAttack

but nothing compiles!

example code:

class LinearADSR
{
public:
    void triggerAttack() { }    
};

class JerobeamBlubb : public gen
{
public:
    void triggerAttack() { adsr.triggerAttack(); }

protected:
    LinearADSR adsr;
};

Upvotes: 1

Views: 1441

Answers (1)

gsamaras
gsamaras

Reputation: 73366

In general, a member function pointer differs from usual pointers, since it has to be used with an instance of its class.

So change your code to this:

class LinearADSR
{
public:
    void triggerAttack() { }    
};

class JerobeamBlubb
{
public:
    void (LinearADSR::*triggerAttack)();
protected:
    LinearADSR adsr;
};

int main()
{
   JerobeamBlubb a;
   a.triggerAttack = &LinearADSR::triggerAttack; 
}

About your failed attempts:

  • void triggerAttack() = adsr.triggerAttack; is invalid syntax
  • std::function<void()> triggerAttack = adsr.triggerAttack fails because triggerAttack is a member function, and not a usual function. You need an instance of its class as I explained before.
  • void(*triggerAttack)() = adsr.triggerAttack fails for the same reason as above.

Upvotes: 2

Related Questions