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?
parameters[0]can't be a pointer to afloat, a pointer to anintand a pointer tostd::stringat 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.