I'm making a simple game that has several item objects belonging to the same class. Instead of filling my main function with a never-ending list of objects, I wanted to create a function that does that and then call it at the beginning of the main function, but I realized that they get destroyed once their function ends, like normal variables. Is there a workaround to instantiate all the objects without writing a huge list inside my main function? (The following code isn't the one I am using in my program, it is simplified)
#include <iostream>
class Items
{
public:
std::string name;
int number;
};
void CreateObjects()
{
Items obj1 = {"Obj1", 1};
Items obj2 = {"Obj2", 2};
Items obj3 = {"Obj3", 3};
}
int main ()
{
CreateObjects();
std::cout << obj1.name;
//here I get an error saying "Identifier obj1 is undefined"
}
CodePudding user response:
class Items
{
public:
std::string name;
int number;
};
You declared a class with these variables. Great, let's now create another class with three of these items:
class Objects {
public:
Items obj1, obj2, obj3;
Objects() : obj1{"Obj1", 1},
obj2{"Obj2", 2},
obj3{"Obj3", 3}
{
}
};
Mission accomplished, you don't even need a separate function! Just instantiate an Objects
class in your main, as a local variable, and you're done:
Objects objects;
std::cout << objects.obj1.name;
CodePudding user response:
obj1
is not in the scope of the function you're using it. This is a very fundamental concept for languages from the C/C /Java/JS/F#/… range of programming languages: Variables aren't accessible from outside the {} they were defined in (their scope). In your case, at the point you're trying to access them, they don't even exist anymore: all three obj1/2/3
were destroyed at the end of CreateObjects
.
So, in your use case, you'd probably write this completely different¹. But you can do things like
#include <iostream>
#include <string>
#include <tuple>
class Item {
public:
std::string name;
int number;
};
auto createStuff() {
Item obj1{"Obj1", 1};
Item obj2{"Obj2", 2};
Item obj3{"Obj3", 2};
return std::tie(obj1, obj2, obj3);
}
int main() {
auto [a,b,c] = createStuff();
std::cout << "a: " << a.name << " b: " << b.name << " c: " << c.name << "\n";
}
¹ (obsoleted by edit)