Memory layout of derived class

Why is there a vptr:void* in the memory layout of class itemtobuy. Is the class virtual? Is it becoz of the virtual destructor?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

class Item
{
	long long int _id;
public:
	Item(long long int id) :
		_id{id}
	{
	}
	long long int id() const
	{
		return _id;
	}
	// Required to get addresses of members
	friend void print_offsets();
};

/*******************************************************************************

Memory layout:

+-ItemToBuy----------------+
| vptr : void*             | 8 bytes
| _price : int             | 4 bytes
| 8 BYTE ALIGNMENT PADDING | 4 bytes
+-Item---------------------+ Memory may not be continuous with a virtual base
| _id : long long int      | 8 bytes
+--------------------------+

Total size is 24 bytes.

*******************************************************************************/

class ItemToBuy : virtual public Item
{
	int _price;
public:
	ItemToBuy(int price) : Item{123},
		_price{price}
	{
	}
	int price() const
	{
		return _price;
	}
	// Required to demonstrate dynamic_cast
	virtual ~ItemToBuy()
	{
	}
	// Required to get addresses of members
	friend void print_offsets();
};
Last edited on
Is it becoz of the virtual destructor?
Yes. Ignore, didn't see you used virtual inheritance.


You probably want Item's destructor to be virtual too.
Last edited on
I'm not a compiler writer, but removing virtual from the subclass destructor doesn't seem to remove the vtable by itself, based on sizeof(ItemToBuy). But removing the virtual from the destructor and making it just be public inheritance instead of virtual public inheritance reduced the size to 16 instead of 24, which would suggest the vtable is removed.

Apparently preventing the diamond problem (the point of virtual inheritance) also requires a vtable. I assume it does this to allow the two different subclass objects to point to the same superclass. I guess that's why it's called virtual inheritance.
Last edited on
Topic archived. No new replies allowed.