Pointers in classes question

Can someone try to explain to me why the name variable inside this class has to be a pointer? I have wondered this for some time now and would like a simple explanation.


1
2
3
4
5
6
7
8
9
class COOLStudent {
public:
  char *name;
  int studentID;
};
int main() {
  COOLStudent student;
  student.name = "Bob";
}


For example, why can't it look like this?


1
2
3
4
5
6
7
8
9
class COOLStudent {
public:
  char name;
  int studentID;
};
int main() {
  COOLStudent student;
  student.name = "Bob";
}


Thanks,
Nick
char * represents a "cstring":
 
char *name = "Gordon Filbert"; // assigns the pointer to a string constant 


char represents a single character:
 
char c = 'N';
closed account (zb0S216C)
It's used to point to an array of characters - It's C's way of representing strings. The string you've assigned to student.name is constant, and therefore, cannot be changed. However, attempts to change the characters inside the string will result in undefined behaviour (a non-constant pointer to constant data).

The modern string is std::string.

Wazzak
Last edited on
Topic archived. No new replies allowed.