Victor
Victor

Reputation: 470

Pointer to member function in virtual function

Is it possible to call a member function from an overriden virtual function? Compiler tells me that the member function has no address (lvalue required as unary '&' operand). I would like to do something like:

class Virtual
{
public:
    virtual void f() = 0;
};

class Real : public Virtual
{
public:
    void f() override { g(&Real::h()); }

private:
    void g(bool (Real::*p)() );
    bool h();
};

However, inside f(), any member pointer statement is invalid (&Real::h(), std::mem_fn(&Real::h()), std::function<bool<void>(h) etc) because it does not consider it an l-value (namely, it does not have an address). I think the reason is that virtual functions are evaluated at run time and that this member pointer must be evaluated at compilation time. Then, is there any alternative?

Thank you!

Upvotes: 0

Views: 103

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

The error message already gives a good hint on what is wrong here:

<source>:10:27: error: cannot take the address of an rvalue of type 'bool'
    void f() override { g(&Real::h()); }
                          ^~~~~~~~~~

Real::h() is bool. Correct syntax to get a pointer to the member function is

    void f() override { g(&Real::h); } 
                           //     ^  -------- no () !!!

Upvotes: 2

Related Questions