Using a String Value to Create New Object

I have created a very simple class Movie which allows several attributes of a movie to be stored and accessed, ex Title, Director, Rating, etc.

I would like to implement some code that allows new Movie objects to be created dynamically depending on how many movies the user would like to input.

I have overloaded the '+' operator to allow an int to be concatenated with a string ("string" + 1 = "string1"), and I basically want to iterate the int in a loop until the user is done inputting movies. Each new movie object should be referenced with using the string+int that is updated each iteration. For example, the first movie will be created as follows: Movie mov1(); second movie Movie mov2() etc.

My problem is how to get C++ to evaluate the string such that I can use its value as the name of a new object. If I implement the following code:

1
2
3
4
5
6
int n = 1;
do {
string s = "mov" + n;
Movie s();
n++;
} while (!QUIT);


the compiler will try to create every Movie object with the reference s. This of course will not work for me. I've been told that I can use the <map> or <vector> libraries to do this, but I know very little about using these.

Any suggestions are greatly appreciated here.
Last edited on
Why not use a pointer and allocate the memory dynamicly?
1
2
3
4
5
6
7
8
9
10
cout<<"How many movies?";
cin>>NUMBER; //use getline()
Movie *movie;
movie=new Movie [NUMBER];
for (int i=0;i<NUMBER;i++)
{
cout<<"Title?";
cin>>movie[i].title; //again: getline()
... //etc.
}
@Scipio: I'd avoid using a pointer initially. The OP been unfamiliar with vector's indicates that they'd have a raft of memory management issues. IMO anyways.

@Johnny: Vector's are dynamically sized lists. You can use them to store an unknown number of objects.

1
2
3
4
5
6
7
8
vector<Movie> movieList;

// Get use details
while (userEnteringData) {
 Movie theNewMovie = Move();
 theNewMove.title = "Titanic";
 movieList.push_back(theNewMovie);
}

That pseudo-code should give you an idea of how to do it.

Yes, it'd be more efficient to do it with pointers because you wouldn't have to incur a copy-construct call to create a new object. However, then you have to manage you own memory. A fair trade-off imo.
Topic archived. No new replies allowed.