-1

I am very new to programing in general!

so I'm building a program that simply takes information about a user and stores it in a object. So each time a new user comes along I will need a new object with a new name (this is just a program I'm building to practice). I know I have too allocate space on the heap, but how do I know how much space I will need if I don't know how many objects I want to net? I think what I need to do is allocate memory on the heap with in the function that creates the obj so each time the function is called I get the required memory? I read something where someone suggested using vectors so I brief learned a intro about those but when I try this

string objname;
cin >> objname;
vector<string> v;
v.push_back(objname);
usersclass v.back();
v.back().somefunc();

An error occurs which I honestly didn't think it would be any different from:

string objname;
cin >> objname;
usersclass objname;
objname.somefunc();

Please give me a example this isn't for school or anything I'm teaching myself.

3 Answers3

4

You cannot name an object at runtime. In fact, at runtime all of those nice variable names are gone, replaced by addresses and offsets by the compiler and linker when you built the program.

What you can do is std::map<std::string, usersclass> names; and use it with names[objname].somefunc()

std::map manages all of the storage for you so you don't have to allocate or deallocate anything.

Documentation on std::map

user4581301
  • 33,082
  • 7
  • 33
  • 54
0

You are trying to do strange things, since vector v contains strings only, and you are simply writing incorrect code.

I assume that you want to create usersclass object, so you need a constructor which takes std::string as argument, and your code should be something like this.

class usersclass {
public:
    usersclass(const std::string& arg) : m_string(arg) {};
    void somefunc() { /* 'dunno, maybe std::cout << m_string' ? */ }
private:
    std::string m_string;
}

// somewhere in main()
string objname;
cin >> objname;
usersclass userobject{ objname };
userobject.somefunc();

But overall, I would recommend to read any beginner book from here. It would be very helpful for you.

Community
  • 1
  • 1
Starl1ght
  • 4,422
  • 1
  • 21
  • 49
0

I haven't yet looked into std::map so I can comment on that but yeah Starl1ght is right, incorrect code I really didn't understand obj/classes this worked in case another beginner needs a super simple example program:

int main()
{
std::vector<newclass> vnewclass;
int x(1);
int z(0);
int c;
while(x == 1)
{
    std::cout << z << std::endl;
    newclass objs;
    objs.printhi();
    objs.enterdata();
    objs.printdata();
    vnewclass.push_back(objs);
    std::cout << "add obj ?" << std::endl;
    std::cin >> x;
    z++;
}
std::cout << "what obj would you like to view ?" << std::endl;
std::cin >> c;
vnewclass[c].printdata();
return 0;
}