C++ function pointer to a member function - which address does it receive?

元气小坏坏 提交于 2019-12-07 16:05:23

问题


Assuming I have this class:

class Shape
{
public:
    int value;

    Shape(int v) : value(v) {};

    void draw()
    {
        cout << "Drawn the element with id: " << value << endl;
    }
};

and the following code (which works)

    Shape *myShapeObject = new Shape(22);

    void (Shape::*drawpntr)();
    drawpntr = &Shape::draw;

    (myShapeObject ->*drawpntr)();

I have a drawpntr function pointer to a void-returning 0-arguments function member of the class Shape.

First thing I'd like to ask:

drawpntr = &Shape::draw;

the function is a member function and there's no object here.. what address does drawpntr receive? The class shouldn't even exist

I agree with the line

(myShapeObject->*drawpntr)();

because I understand I cannot de-reference a function pointer to a member function (no object -> no function), but what address is actually stored in drawpntr?? There's no object when the

drawpntr = &Shape::draw;

line is invoked.. and the class shouldn't exist either as an entity


回答1:


All member functions share the same code, so they have the same address in the code segment of memory. Member functions operate on different instances only because they are implicitly passed different values of this pointer. They are not tied in any way to any of the instances on which they operate. The actual value of drawpntr could be determined statically if the function is non-virtual, or dynamically (through the vtable) if the function is virtual.



来源:https://stackoverflow.com/questions/12765228/c-function-pointer-to-a-member-function-which-address-does-it-receive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!