-2

I was trying to run this simple block of code and I got the error: expression must have class type for tom.name and tom.id. What have I done wrong here?

#include <iostream>
#include <string>
using namespace std;

class Student
{
    string name;
    int id;
    int age;
};


int main()
{
    Student* tom = new Student;
    tom.name = "tom";
    tom.id = 1;
}
shadowByte
  • 93
  • 1
  • 1
  • 6

1 Answers1

1

You are accessing the pointer incorrectly. Accessing inner variables from a pointer require -> instead of the . operator.

Switch your code:

Student* student_ptr = new Student;
student_ptr->name = "Tom";
student_ptr->id = 1;

Alternatively, if you really want to use the . operator, you can do:

Student* student_ptr = new Student;
(*student_ptr).name = "Tom";
(*student_ptr).id = 1; // the more you know
Frontear
  • 1,150
  • 12
  • 25