Monday, July 27, 2009

Help making a copy constructor in C++?

Trying to make a copy constructor to make a copy of a MovieDatabase object. The Movies have a title, director, cast, genre, and number of hits. But I'm not sure if I need to use those variables or not since on the homework, the professor says to declare them in a different .h file.





MovieDatabase::MovieDatabase(const MovieDatabase%26amp; rhs)


{


title = new string (*(rhs.title)); //Makes a copy of title.


director = new string (*(rhs.director)); //Makes a copy of director.


cast = new string (*(rhs.cast)); //Makes a copy of cast.


genre = new MovieGenre (*(rhs.genre)); //Makes a copy of genre


Movies = new Movie[50]; //Makes a copy of Movie_Objects.


strcpy(Movies, rhs.Movies); //Copies Movie_Objects.


}

Help making a copy constructor in C++?
strcpy(Movies, rhs.Movies); //Copies Movie_Objects.





That's bad, you're copying Movie objects, and not strings (strcpy is there to copy a C string).


You need to loop over all 50 movies and copy them one by one:





for (int i=0; i%26lt;50; i++)


Movies[i]=rhs.Movies[i];





(Note that you also need a copy constructor in the Movie class, to make this work)





Also, i see that most of your members are pointers - that's not necessary. I.e. if you declare title as "std::string", like this:


std::string title;


then the copying is easier, you don't need to allocate memory:


title=rhs.title;


and also, you don't need to delete the object in the destructor, which you definitely should do if you allocate the object with new.

salary survey

No comments:

Post a Comment