we cannot create object of any class in switch case directly. Why? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

we cannot create object of any class in switch case directly. Why?

#include <iostream> using namespace std; class Student{ string name; }; int main() { int n=1; switch(n){ case 1: Student s1; break; default: break; } return 0; }

25th May 2024, 5:49 PM
Rishi
Rishi - avatar
7 Antworten
+ 7
Notice that the switch statement body is enclosed in braces { }. These define the beginning and end of a basic block of code. Any variables (or objects) defined with a basic block exist only within that block. It is a principle known as scope. When execution goes outside the block, the variables defined within the block go out of scope and are discarded. They become inaccessible.
26th May 2024, 3:15 AM
Brian
Brian - avatar
+ 3
you can use pointers #include <iostream> using namespace std; class Student{ string name{"John"}; public: Student()=default; Student(const string& n):name(n){ cout<<name<<endl; } void sayname(){ cout<<"I am "<<name<<endl; } }; int main() { int n=1; Student* s1; switch(n){ case 1: s1 = new Student(); break; case 2: s1 = new Student("Jane"); break; default: break; } s1-> sayname(); }
26th May 2024, 4:04 AM
Bob_Li
Bob_Li - avatar
+ 1
add braces: switch(n) { case 1: { Student s1; break; } default: break; }
26th May 2024, 11:21 AM
john ds
john ds - avatar
+ 1
john ds s1 still only exists within the block scope of the braces.
26th May 2024, 11:55 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li my bad, i thought he had a compiler error and as long he not use it anywhere else outside the block i assumed he asking why cannot compile it
26th May 2024, 12:04 PM
john ds
john ds - avatar
0
Please show your code.
25th May 2024, 6:08 PM
Wilbur Jaywright
Wilbur Jaywright - avatar
26th May 2024, 6:14 AM
Bob_Li
Bob_Li - avatar