'Getting an identifer is undefined issue C++
I want to make it so my program will create an object based on user input. When I run the program I get the error "identifier "plant" is undefined" on the first call of plant which is "while(plant.getDays() > 0){".
#include "Carrot.h"
#include "Potato.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int gameState = 1;
cout << "WELCOME TO THE CROP GAME" << endl;
while(gameState == 1){
cout << endl << "PICK A CROP TO GROW" << endl;
cout << "1:CARROT - SHORT" << endl;
cout << "2:POTATO - LONG" << endl;
int userGameChoice;
cin >> userGameChoice;
while(userGameChoice < 1 || userGameChoice > 2){
if(userGameChoice == 1){
Carrot plant;
cout << "YOU HAVE CHOSEN TO GROW CARROTS" << endl;
}
else if(userGameChoice == 2){
Potato plant;
cout << "YOU HAVE CHOSEN TO GROW POTATOES" << endl;
}
else{
cout << "INVALID CHOICE" << endl;
cin >> userGameChoice;
}
}
while(plant.getDays() > 0){
int userChoice;
//STATS
plant.DisplayStats();
//MENU
plant.Menu();
Solution 1:[1]
You declare variables plant
in nested code blocks, so they cannot be seen in the outside blocks, they are visible only in the specific branches of if-else
statement. When the compiler gets to your while
loop, there is no visible variable.
If you want it to work, you need to declare variable before you use them in a visible scope, like:
int main(){
int gameState = 1;
cout << "WELCOME TO THE CROP GAME" << endl;
while(gameState == 1){
cout << endl << "PICK A CROP TO GROW" << endl;
cout << "1:CARROT - SHORT" << endl;
cout << "2:POTATO - LONG" << endl;
int userGameChoice;
Plant *plant;
cin >> userGameChoice;
while(userGameChoice < 1 || userGameChoice > 2){
if(userGameChoice == 1){
plant = new Carrot()
cout << "YOU HAVE CHOSEN TO GROW CARROTS" << endl;
}
else if(userGameChoice == 2){
plant = new Potato()
cout << "YOU HAVE CHOSEN TO GROW POTATOES" << endl;
}
else{
cout << "INVALID CHOICE" << endl;
cin >> userGameChoice;
}
}
while(plant->getDays() > 0){
int userChoice;
//STATS
plant->DisplayStats();
//MENU
plant->Menu();
}
delete plant;
}
}
However, if you want it to work, Carrot and Potato need to be descendants of some Plant
class. Here, plant
is a pointer to object of class Plant
and the object is created dynamically, using new
keyword inside of the if-else
branches. Since it's created dynamically, it also needs to be deleted after all. You probably need to understand more about polymorphism in C++, the source linked in your comments might be useful for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |