-1

So I am trying to make a std::vector<> that will contain my Components:

class Component
{
private:


public:
    Component();

    void update();

    ~Component();
};

the vector is inside my Object Class :

class Object
{
private:
    std::vector<?> m_Components;
public:
    Object();

    void addComponent(? component)
    {
        m_Components.push_back(component);
    }

    ~Object();
};

So I have tried using templates but it failed error : use of a variable template requires template argument list

Do I need to use templates ? if yes how ? thanks for your help!

Edit : My Components are derived from the Component class

Rex
  • 50
  • 1
  • 7
  • No, you do not need to use templates. However, is your `vector` storing instances of the `Component` class itself, or instances of classes derived from `Component`? It makes a big difference. In the former case, you can use `vector`, in the latter case you have to use `vector` instead to avoid [slicing the objects](https://stackoverflow.com/questions/274626/) – Remy Lebeau Oct 10 '18 at 01:13
  • of derived classes I will edit my post – Rex Oct 10 '18 at 01:14
  • I tried vector but when make a Component2:Component class it gives me this error : conversion to inaccessible base class "Component" is not allowed – Rex Oct 10 '18 at 01:21
  • Use `class Component2 : public Component` instead. `class Component : Component` uses *private* inheritance, but you need *public* inheritance. Also, `~Component()` needs to be declared as `virtual` if you intend to ever `delete` a derived object via a base `Component*` pointer. – Remy Lebeau Oct 10 '18 at 01:21

1 Answers1

1

Since you are dealing with polymorphic classes, you need to use Component* where you currently have ?, because polymorphism works only with pointers/references, and also to avoid slicing any objects you add to the vector, eg:

class Object
{
private:
    std::vector<Component*> m_Components;
public:
    Object();

    void addComponent(Component *component)
    {
        m_Components.push_back(component);
    }

    ~Object();
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770