#How to avoid object slicing

9 messages · Page 1 of 1 (latest)

versed vector
#

I've read up a bit and apparently using pointers should be solving my issues but the terminology is starting to fry my brain.
I'm storing derived class objects in a map of the base class (using shared ptrs which appears to be what's worked best so far).

std::unordered_map<EUID, std::shared_ptr<Body>> entity_map;```
This map is stored inside an entity-manager object which instances a new entity as follows:
```cpp
entity_map.insert({ uid, std::make_unique<Body>(uid, pos) });```
Now my issue is I want to pass in an ID number & return a pointer to the corresponding object but this solution is only able to provide Body*, not pointers for the derived classes which would allow access to methods not defined in the base class. Is there a way to access the  full derived object? 

Pointer return function:
```Body* GetEntityPtr(EUID uid) {
    return entity_map[uid].get();
}```
The following code has error E0144 since the return type does not match:
```DynamicBody* test_body2 = entity_manager.GetEntityPtr(2);```
rancid bridgeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

hidden gazelle
#

it handles some stuff at runtime to be sure the cast is either successfull, or in the cases of failure it will just return a nullptr

versed vector
#

Thanks, I'll look into it

rancid bridgeBOT
#

@versed vector Has your question been resolved? If so, type !solved :)

versed vector
#

Awesome got it to work! for whatever reason the template doesn't like being in the cpp file but i don't care at this stage lol

    return dynamic_cast<T*>(entity_map[uid].get());
}```

```DynamicBody* test_body2 = entity_manager.GetEntityPtr<DynamicBody>(2);```
rancid bridgeBOT
#

@versed vector

It looks like you may have code formatting errors in your message

Note: Make sure to use back-ticks (`) and not quotes (')
Note: Make sure to specify a highlighting language, e.g. `cpp`, after the back-ticks

Markup

```cpp
int main() {}
```

Result
int main() {}
versed vector
#

!solved