C++ Size of classes and subclasses
If a class instance uses 20 bytes, and its subclass uses 24 bytes since it as more members, how is it possible to stor开发者_如何学运维e an instance of the subclass in a variable of the parent class?
Like:
Subclass s;
ParentClass p ;
p = s;
You don't "store" instances "in" pointers. Pointers merely point at the start of the instance in memory.
The pointer object itself contains a memory address, and the space that this takes up is always the same no matter what — or how much — data may be found at that address.
Edit (since the question has changed almost completely)
In the example you've added to your question, the code doesn't do what you think it does. You are not storing a Subclass
in a ParentClass
; instead, you are slicing off the derived bits of s
, and copying only its base bits into p
.
You asked elsewhere how you can fit a Derived
in an array of Base
; you can't.
The pointer size is always identical. It just points to a larger memory region.
Compare:
+-----+
| ptr | ------+
+-----+ |
v
+----------+
| Base |
+----------+
with:
+-----+
| ptr | ------+
+-----+ |
v
+----------+----+
| Derived |
+----------+----+
Where the pointer value in both cases is some fictional address which marks the start address of the memory region that hosts the respective object.
Class instances (i.e. objects) are not stored in pointers. They just occupy memory, subclass instances in general more than class instances. Pointers - as the name says - only point to these objects in memory. The pointer can be compared to an address of a memory block. And the address occupies always the same amount of bytes.
精彩评论