fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Define a simple class
  5. class Student {
  6. public:
  7. string name;
  8. int id;
  9.  
  10. void display() {
  11. cout << "Name: " << name << ", ID: " << id << endl;
  12. }
  13. };
  14.  
  15. int main() {
  16. Student s1; // create object
  17. s1.name = "Alice";
  18. s1.id = 101;
  19.  
  20. Student* ptr = &s1; // create pointer to object
  21.  
  22. // Access members using the arrow operator
  23. ptr->display(); // prints: Name: Alice, ID: 101
  24.  
  25. // Modify members using the pointer
  26.  
  27. ptr->name = "Bob";
  28. ptr->id = 102;//if this line is comment out this shows id of alice .so this ptr is just reassigning the value
  29.  
  30. ptr->display(); // prints: Name: Bob, ID: 102
  31.  
  32. /*if there was another object s2 and ptr was pointing to s2 then first ptr->display will not work.because we didnt set the value;
  33.   it same like int* p=&x;
  34.   *p=10//would change the value x;
  35.   this *p is now written as p-> and as class has many info p->variable(which has to be set )should be written */
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Name: Alice, ID: 101
Name: Bob, ID: 102