Please note that i'm a newbie with classes. Here's an idea of what i want (and need to make my code more clean and versatile)
Inside my function StartupRoutine(std::map<std::string, MyClass*>& mymap)
:
MyClass myobj[2];
myobj[0] = new MyClass(/* constructor parameters */);
myobj[1] = new MyClass(/* constructor parameters */);
/* do some stuff and call some setters */
mymap.insert(std::pair<std::string, MyClass*>("something", myobj)); /* myobj should be equal to &myobj[0] right? */
I'm calling that from the main
. I want the classes to stay until i call delete
.
I want to do that in order to easily access class methods with both objects with an offset like: mymap["something"] and mymap["something"]+1
.
And i'd like to use the same map
for single objects and arrays of 2 or 4 objects, for several reasons,
I have tried many many ways and google for hours.
I tried something like the example above.
Then i tried to initialize myobj
as a single pointer:
MyClass* myobj;
myobj = new MyClass(/* constructor parameters */);
myobj+1 = new MyClass(/* constructor parameters */);
which i'm pretty sure it's really wrong because i'm trying to access a memory address i'm not supposed to.
EDIT: Thanks everyone for the help, i'm going to answer the comments here: about the new
statement you guys are right i'm an idiot and forgot about that after hours of trying. Here a more detailed explanation of what i'm doing:
I'm making a simple game with SDL and i have my class for the textures. I want to map my texture (probaly there are better ways to handle them but that's the best solution i came up with to make my code more versatile (and better looking)). So most of the textures are in the map will be a single object, but in some cases, for the animations, i use a seamless texture and i need more instances of the same image but with different coordinates (which are both attributes of the class). I'd like to handle normal textures as single objects and seamless textures as arrays of 2 or 4 objects in the same map. i know i can simply map them individually like map["water1"]
and map["water2"]
but to me it's very very ugly and i'm trying to find a better solution.
BTW I'm doing all of this for educational purposes. PS: sorry for my absence but in weekends i do work.
SECOND EDIT: what if i use malloc and instead of new and do this:
MyClass* MyObj = (MyClass*)malloc(sizeof(MyClass)*2);
*MyObj = MyClass(/* constructor parameters */);
*(MyObj+1) = MyClass(/* constructor parameters */);
mymap.insert(std::pair<std::string, MyClass*>("something", MyObj));
for some reason it crashes when i try to call a class method like:
mymap["something"]->MyMethod();