Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ displaying the wrong object

Tags:

c++

I am a beginner in C++ and I am trying to create 2 classes that stores Movie for each Day.
For example, there are 2 movies on saturday. One of the movie is Batman and the other is Spiderman. So the object Day saturday should store 2 different movies. However, the problem is when I tried to display the object stored in saturday with the function showAllMovies() within the class Day, it showed the last movie only. Any idea what I have done wrong?

EDIT: I can only use these libraries since my assignment won't allow me to use other libraries.

<iostream>, <iomanip>, <fstream>, <cmath>
#include <iostream> 
using namespace std;

class Movie {
private:
    char* name;
public:
    void setName(char* n) {
        name = n;
    }
    char* getName() {
        return name;
    }
};

class Day {
private:
    int movieCount = 0;
    Movie movie[20];
public:
    void addMovie(Movie p) {
        movie[movieCount] = p;
        movieCount++;
    }
    void showAllMovies() {
        for (int i = 0;i < movieCount;i++) {
            cout << "Index: " << i << ", Name: " << movie[i].getName() << endl;
        }
    }
};

int main()
{
    Day saturday;
    int numOfMovies = 0;

    cout << "Input the number of Movies: " << endl;
    cin >> numOfMovies;

    cout << "Input the name of Movie: " << endl;
    for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

    //Show all the name of movies
    cout << "All movies on saturday: " << endl;
    saturday.showAllMovies();

    return 0;
}

Input: 2 Batman Spiderman

Output:
enter image description here

I am expecting to get something like

All movies on saturday:
Index: 0, Name: Batman
Index: 1, Name: Spiderman

Thanks to everyone helping me out. The Solution is to change

char movieName[10];

to

char *movieName = new char[10];
like image 814
Bsonjin Avatar asked Sep 15 '26 21:09

Bsonjin


1 Answers

for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

when you call setName internally you make name (which is field of Movie object) point to movieName - however, movieName dies on the next iteration of the for loop due to scope.

The last instance of movieName should also not be accessed after the loop ends.

like image 130
Giorgi Moniava Avatar answered Sep 17 '26 12:09

Giorgi Moniava