I'm just going over classes but I get this error which stops me blank. I've looked through other threads but no clue what's wrong with my code? I've commented the code which is the issue.
class myClass { //Class which might cause an issue? Don't see whats wrong with it.
public:
myClass(string nm) {
setName(nm);
}
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
int main() {
cout << "Task 1, Task 2, Task 3, Task 4 ?" << endl;
int answer;
cin >> answer;
switch (answer)
{
case 1://Practising Classes
CRectangle area;
cout << "Enter two numbers \n";
cin >> area.x;
cin >> area.y;
cout << "Area is: "<< area.findArea() << endl;
break;
case 2://Practising Classes
AddNumbers myObj1;
myObj1.getNumbers();
cout << myObj1.addNumbers() << endl;
case 3: //Practising Classes
birthdays b1;
cout << "Welcome to Birthdays! \n";
bool bool1 = false;
do {
cout << "Do you want to enter some data (1) or retrieve some? \n";
int answer;
cin >> answer;
switch (answer)
{
case 1:
b1.setdata();
break;
case 2:
b1.getdata();
}
} while (bool1 == false);
case 4: // This causes the error. // Testing out Constructors
myClass object("David");
myClass object2("Amy");
cout << object.getName();
}
system("PAUSE");
}
Those case
"statements" are actually labels, like goto
. They do not begin a new scope. When a condition is found, execution "jumps" to the relevant case label and continues from there.
The language's rules insist that you cannot "jump" over initialisations, as allowing this in a consistent and predictable way would require more complex standard wording.
Put your cases in a scope of their own to "insulate" the declarations and prevent them from "leaking" into the next case, which is what the compiler is concerned about.
For example:
case 1: { //Practising Classes
CRectangle area;
cout << "Enter two numbers \n";
cin >> area.x;
cin >> area.y;
cout << "Area is: "<< area.findArea() << endl;
break;
}
I've added the {
and the }
. These are not part of the syntax of switch
/case
, but just standalone scope blocks, much like the inner ones here:
int main()
{
int x = 42;
{
int x = 999; // a different x!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With