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
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 ofdrawpntr
could be determined statically if the function is non-virtual, or dynamically (through the vtable) if the function is virtual.