Tiago Costa
Tiago Costa

Reputation: 4251

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 store an instance of the subclass in a variable of the parent class?

Like:

Subclass s;
ParentClass p ;
p = s;

Upvotes: 1

Views: 960

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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.

Upvotes: 8

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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.

Upvotes: 6

Jiri Kriz
Jiri Kriz

Reputation: 9292

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.

Upvotes: 2

Related Questions