Home > Enterprise >  Returning a child class from a parent class array C
Returning a child class from a parent class array C

Time:11-18

class Component {
    // Code here
};

class TransformComponent : public Component {
    // Code here
};

class Entity:
    public:
        Component components[25];
        
        TransformComponent *getTransform() {
            for(int i = 0; i < 25; i  ) {
                if(typeid(components[i]) == typeid(TransformComponent())) {return *(components   i);}
            }
        }
};

I have an array of components, and inside could be any child class of "Component", like "TransformComponent". The thing is, when compiling, the computer thinks that the components array is only populated with "Component" objects. The function is supposed to return a "TransformComponent", and the compiler sees that as an error, even though the element in the array I am returning is a TransformComponent. Is there any solution to this (preferably simple)?

CodePudding user response:

'I have an array of components, and inside could be any child class of "Component", like "TransformComponent".' - this statement is false. If you have an array of Component objects, then at each index in the array, there's exactly a Component-typed object and not a descendant.

If you'd like to store multiple (e.g. Base-Descendants) types, you have two main choices:

  • use container of (smart) pointers: std::vector<std::unique_ptr<Component>> components
  • use variants: std::vector<std::variant<Component, TransformComponent/*, ... other types*/> components>;
  • Related