0

This code should work...

Here's the code: #include <iostream> using namespace std; class palpatine { public: string name = "Palpatine"; void lightning () { cout << "ZZap" << endl; } }; class yoda { public: string name = "Yoda"; void lightSaber () { cout << "Vrrroom sschllasshh" << endl; } }; int main() { cout << "Player 1, choose a name" << endl; string p1Name; cin >> p1Name; cout << "Player 1,choose a character" << endl; int p1Choice; cout << "Dark Side:" << endl << "1: Palpatine" << endl << "Light Side:" << endl << "2: Yoda" << endl; cin >> p1Choice; if (p1Choice == 1) { palpatine p1; } else if (p1Choice == 2) { yoda p1; } else { cout << "Sorry" << endl; } cout << "Player 2, choose a name" << endl; string p2Name; cin >> p2Name; cout << "Player 2,choose a character" << endl; int p2Choice; cout << "Dark Side:" << endl << "1: Palpatine" << endl << "Light Side:" << endl << "2: Yoda" << endl; cin >> p2Choice; if (p2Choice == 1) { palpatine p2; } else if (p2Choice == 2) { yoda p2; } else { cout << "Sorry" << endl; } cout << p1Name << ": " << p1.name << endl << p2Name << ": " << p2.name << endl << "Fight!" << endl; return 0; } It seems like it gives me the error because I try to use the class even though I haven't technically declared an object. I want to declare it when it actually runs and the user has given some input, which should work theoretically, but the compiler doesn't see it like that. Any way I can get around this problem? Thanks!

31st Jan 2020, 5:15 PM
THOMAS WALD
THOMAS WALD - avatar
1 Respuesta
0
You need Polymorphism. 1. Your current code in code playground https://code.sololearn.com/cj9aAJk5kCWQ/?ref=app 2. Current error message: 62:31 error: 'p1' was not declared in this scope. p1 declared at either line 35 or line 38 belongs to the if-else code block and cannot be called at line 62. Solution is to declare at beginning of main() 3. Lesson to Polymorphism: https://www.sololearn.com/learn/CPlusPlus/1910/ Lesson to virtual functions: https://www.sololearn.com/learn/CPlusPlus/1911/ Lesson to pointers: https://www.sololearn.com/learn/CPlusPlus/1631/ 4. Corrected version : https://code.sololearn.com/cWTxhT8WElO2/?ref=app
31st Jan 2020, 5:21 PM
Gordon
Gordon - avatar