Dynamic Allocation

Ok, so I keep finding all kinds of information on this, and I know how it all works, but my brain is just not wrapping around how to accomplish this....

I want to dynamically allocate to the variable of an already created object.

Like say I have class: ObjA, ObjA has some simple variable in it called PT1, PT1 is waiting to become a pointer to a Struct that has been dynamically allocated. In this way a specific group of data is then attached to the object.

How would I go about doing something like this?


EDIT: Nvm, I figured it out... templates rule!

For those interested and maybe for some critiques, here's how I did it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <memory>

struct Component
{
	int HP;
	std::string Name;

	Component(int h, std::string s) : HP(h), Name(s) { };
};

template <class T>
class Entity
{
public:
	int id;
	T data;

	int GenerateID()
	{
		static int newID = 0;
		return newID++;
	};

	Entity(T dat) : id(GenerateID()) { data = std::move(dat); };
};

int _tmain(int argc, _TCHAR* argv[])
{
	std::cout << "Test Ha!" << "\n";
	std::unique_ptr<Component> G(new Component(5,"Player"));

	Entity<std::unique_ptr<Component>> E(std::move(G));

	std::cout << E.data.get()->Name << "\n";

	system("pause");
	return 0;
}
Last edited on
Topic archived. No new replies allowed.