Question about sizeof function and class member

 class B
{
   public:
     int a;
     void fn();
}

If I create an object B using

B* pb = new B;

Where is the memory fn () located?

Is there a pointer in the object pointing to the fn () memory location?

If so, why does sizeof (B) return a value as if it doesn't have a pointer to an object?

+3
source share
4 answers

Where is the memory fn () located?

Since this is a normal function, somewhere in the code section of your program. This place is the same for all instances of the class. In fact, it has nothing to do with creating Bthrough pb.

Is there a pointer in the object pointing to the fn () memory location?

No. For a normal member function, this is not required, since the address is known at compile time (or, at the latest, at connection time); therefore, it should not be stored separately at run time.

. ( " " "vtable" ). vtable, vtable. , / Base Derived, , ; , , . vtable sizeof.

+15

:

class B
{
   public:
     int a;
     void fn();
};

C-:

struct B
{
   int a;
};

void fn(B* bInstance);

++ bInstance . . , , , sizeof (B)?

+6

( vtable) , .

+2

1) B * pb = new B . , , . , (shared_ptr, auto_ptr. Scope_ptr) .

2) , null, , int.

3) fn() , vtable .

+1
source

Source: https://habr.com/ru/post/1703435/


All Articles