I’m working on a project for a class, written in C++. I keep getting a weird error when trying to build my code, saying that a symbol isn’t declared in its scope. This is probably a simple fix, but I can’t find on the forums, and don’t know enough about c++ to figure it out on my own. Here’s the code:
#include "Menu.h"
#include "MovieCollection.h"
#include "Movie.h"
Menu::Menu() {
MovieCollection mc("Collection.txt");
}
void Menu::displayTopMenu(){
MovieCollection mc("Collection.txt");
cout<<"Press:\n"<<
"1- To list all movies\n"<<
"2- To search by title\n"<<
"3- To search by year\n"<<
"4- To search by Director\n"<<
"5- To add a movie to the collection\n"
"6- to remove a movie from the collection\n"
"0- To exit the program\n";
}
void displaysub1(){
mc.listAll();
// This is the bit that gives me the "out of scope" error
}
And here’s the Menu.h file, as well…
#ifndef MENU_H_
#define MENU_H_
#include "Movie.h"
#include "MovieCollection.h"
#include <iostream>
using namespace std;
class Menu {
public:
Menu();
void displayTopMenu();
void displaysub1();
};
#endif /* MENU_H_ */
Message is as such:
Multiple markers at this line
– ‘mc’ was not declared in this scope
– Symbol ‘mc’ could not be resolved
– Method ‘listAll’ could not be
Also, I tried declaring MovieCollection mc as a private instance variable; not much has changed
Found the issue: I wanted to have each method as Menu::displaysub1()
mcis local toMenu::displayTopMenu(), as well as your constructor. If you need to access it outside of that method then it needs to be declared at a higher scope, probably best as an instance variable.Also note that
displaysub1()is not a member function (but it should be, I think this was likely just an error), so it will still not have access to your class’ member variables. If it needs to access them you will have to pass it as an argument (or makemcstatic, but I see no reason to do that).Further reading re: variable scope/lifetime in C++.