Function pointers, function pointers, and pointer Functions

Source: Internet
Author: User

Function pointers, function pointers, and pointer Functions
(1/2) Type

A normal function pointer cannot be assigned the address of a member function.

Int (* pFunc )();

PFunc is a function pointer, while int (*) () is a type.

The member function address must be assigned to the member function pointer.

class Base{public:    int func() { return 1; }};int main(){    int (*pFunc)();    pFunc = &Base::func;  //error: cannot convert 'int (Base::*)()' to 'int (*)()' in assignment    return 0;}
class Base{public:    int func() { return 1; }};int main(){    int (Base::*pFunc)(); // OK    pFunc = &Base::func;    return 0;}

Again:

class Base{public:    int func() { return 1; }};class Derived : public Base{public:    int foo() { return 1; }};int main(){    typedef int (Base::*FuncPtr)();    FuncPtr fPtr = &Derived::foo; // error    return 0;}

Mandatory type conversion required

......

FuncPtr fPtr = (FuncPtr)&Derived::foo;  // OK

In turn, the base class member function address can be assigned a pointer to the member function of the derived class.

class Base{public:    int func() { return 1; }};class Derived : public Base{public:    int foo() { return 1; }};int main(){    typedef int (Derived::*FuncPtr)();    FuncPtr fPtr = &Base::func;  // OK    return 0;}
(2/2) Call
class Base{public:    virtual void func(int i) { cout << "Base: " << i << endl; }};class Derived : public Base{public:    virtual void func(int i) { cout << "Derived: " << i << endl; }};int main(){    typedef void (Base::*FuncPtr)(int);    FuncPtr fPtr = &Base::func;    Base b;    (b.*fPtr)(2);    Derived* dPtr = new Derived();    (dPtr->*fPtr)(2);    Base* bPtr = new Derived();    (bPtr->*fPtr)(2);    return 0;}

Output:

Base: 2
Derived: 2
Derived: 2

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.