Derived objects in base class containers

I have heard, that's problematic if a container is instantiated with a base class type and will get filled with derived class types. Because their size is different.
But if both base and derived classes have the same amount of members, then their objects size should be equal. Is that a way for storing them all in the same container?

Here an example:
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
#include <iostream>
#include <vector>

struct Creature
{
    std::string name;
       
    Creature( std::string n = "") : name(n) {}
    virtual std::string talk() = 0;
};
struct Human : Creature
{
    Human(std::string name) : Creature(name) {}
    std::string talk() { return "Hello, I'm "+name+"."; }
};
struct Lion : Creature
{
    std::string talk() { return "Roaar"; }
};

int main()
{
    std::vector<Creature*> vec;
    
    for (int i = 0; i < 8; ++ i)
    {
        vec.push_back( new Human("Tarzan") );
        vec.push_back( new Lion() );
    }
    
    for (Creature * c : vec)
    {
        std::cout << c->talk() << '\n';
    }
}

What are you meanings about?
Line 23: You're storing a polymorphic pointer in your vector. All pointers have the same size, so what you're doing is perfectly acceptable. There is no requirement that polymorphic derived classes have the same size.

What are you meanings about?

I don't know what that question means.
Last edited on
Your container holds pointers, so the size discussion is not relevant anyway (it also has memory leaks: it should store std::unique_ptr<Creature>).

What you likely heard was the fact that it's undefined behavior to iterate an array of derived objects using a base pointer. The behavior is undefined even if their sizes match.

The standard defines that in http://eel.is/c++draft/expr.add#6 as follows:

For addition or subtraction, if the expressions P or Q have type “pointer to cv T”, where T and the array element type are not similar, the behavior is undefined. [ Note: In particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type. — end note ]

("similar" here means differing in constness/volatility. Same size does not make them similiar. If you follow the link, you can click on that word for its definition)

Last edited on
Topic archived. No new replies allowed.