C ++ function pointer to a member function - what address does it get?

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 function element void-returning the 0-argument of the Shape class.

First of all, I would like to ask:

 drawpntr = &Shape::draw; 

the function is a member function and there is no object .. what address does drawpntr do? Class should not even exist

I agree with the line

 (myShapeObject->*drawpntr)(); 

because I understand that I can’t cancel the link to the function-member function (no object β†’ no function), but what address is actually stored in drawpntr ?? No object if

 drawpntr = &Shape::draw; 

a string is called and the class should not exist as an object

+2
source share
1 answer

All member functions have the same code, so they have the same address in the memory code segment. Member functions work only in different cases, because they implicitly pass different values ​​of the this pointer. They are in no way associated with any of the cases when they act. The actual drawpntr value can be determined statically if the function is not virtual or dynamically (via vtable ) if the function is virtual.

+7
source

All Articles