The question of pointers to class member functions: are pf = base::print; and pf = & base::print; equivalent?

1. The code is as follows:

-sharpinclude <iostream>
using  namespace std;

class base {
public:
    int a = 10;
    virtual void print() { cout << "In Base" << endl;}
};

class derived : public base {
public:
    void print() { cout << " In devired" << endl;}
};
void display(base *pb, void(base::*pf)()) { (pb->*pf)();}

int main() {
    derived d;
    base *pb = &d;
    void (base :: *pf)();
    pf = base::print; //
    //pf = &base::print; // 
    display(pb, pf);
}

2. Use statement 1 and statement 2 to output the same result: In devired . Why?
3. When using statement one pf = base::print , CLION prompts Function "print" must be static. . Is there a problem with CLION?

CPP
Mar.02,2021

The output of

is the same because pf points to the same function, and "In devired" is because pf points to virtual functions.

8.5.1.2.2 For a call to a non-static member function, the postfix expression shall be an implicit (12.2.2, 12.2.3) or explicit class member access (8.5.1.5) whose id-expression is a function member name, or a pointer-to-member expression (8.5.4) selecting a function member ;

8.5.1.2.3 If a function or member function name is used, the appropriate function and the validity of the call are determined according to the rules in 16.3. If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called. Otherwise, its final overrider (13.3) in the dynamic type of the object expression is called; such a call is referred to as a virtual function call.

the address of a non-static member function must be added &. It's not CLION.

8.5.2.1.4 A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses.

quoted from N4741, CPP20 working draft. These two parts of the standards should be the same, if you don't rest assured, consult the relevant documentation according to the compiler settings.

Menu