0

I want to have in GameObject class a vector of objects that inherits from A class, and a template method, that will add new objects of template type to the vector.

But I want to have possibility of using constructors, with parameters of unknown type, so I want to use void pointers array to do that, but I have an error saying:

exited with non-zero status

Here is the code:

#include <iostream>
#include <string>
#include <vector>

class A
{
public:

    virtual void whatever() { std::cout << "okay\n"; }
};

class B : public A
{
public:
    float a;
    std::string b;
    int c;

    void print()
    {
        std::cout << "a,b,c values: " << a << ", " << b << ", " << c << std::endl;
    }

    B(void * parameters[])
    {
        this->a = *(static_cast<float*>(parameters[0]));   
        this->b = *(static_cast<std::string*>(parameters[0]));
        this->c = *(static_cast<int*>(parameters[0]));
    }
};

class GameObject
{
public:
    std::vector<A*> components{};

    template<class T>
    void AddComponent(void * parameters[])
    {
        auto t = new T(parameters);
        components.push_back(t);
    }
};

int main()
{
    float f = 2524.218f;
    std::string s = "str";
    int i = 4214;

    auto g = new GameObject;

    void* ptr[3];

    ptr[0] = &f;
    ptr[1] = &s;
    ptr[2] = &i;

    g->AddComponent<B>(ptr);
    static_cast<B*>(g->components[0])->print();
}

Can you tell me what the problem is and if it's possible, correct the code?

2
  • Did you really mean to assign the same array entry to 3 different variables? This seems like a terrible design choice. Commented Oct 8, 2017 at 18:01
  • 2
    parameters[0] can't be a pointer to a float, a pointer to an int and a pointer to std::string at the same time. Think about what attempting to dereference it as a string when it's not a string will do. And learn about undefined behavior. Commented Oct 8, 2017 at 18:02

1 Answer 1

1
    this->a = *(static_cast<float*>(parameters[0]));   
    this->b = *(static_cast<std::string*>(parameters[0]));
    this->c = *(static_cast<int*>(parameters[0]));

Did you mean:

    this->a = *(static_cast<float*>(parameters[0]));   
    this->b = *(static_cast<std::string*>(parameters[1]));
    this->c = *(static_cast<int*>(parameters[2]));

I.e. use different array indices.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.