0

I decided to retry to learn C++ by my own and now I have a question regarding pointers. I understand what pointers do, but can somebody explain the difference between these two pieces if code?

I have a structure student:

struct student {
    char* name;
    int age;
    int grade;
};

and two ways of outputting it's data:

void printData(student p) {
    cout << p.name << endl;
    cout << p.age << endl;
    cout << p.grade << endl;
}

int main() {
    student ST = { "Dave",20,81 };
    printData(ST);
    return 0;
}

and:

void printData(student* p) {
    cout << p->name << endl;
    cout << p->age << endl;
    cout << p->grade << endl;
}

int main() {
    student ST = { "Dave",20,81 };
    printData(&ST);
    return 0;
}

The question is: why should I stick with pointers if I could just pass a student object to the printData function?

PYPL
  • 1,819
  • 1
  • 22
  • 45

1 Answers1

0

Because it is cheaper. Passing by value creates a new copy. Passing a pointer does not (passing by ref would be a bit cleaner I think). It might not matter in this case because your student has few fields. However, if you have larger objects or a lot of them, then you will start noticing quite a difference in performance. For more information see: What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
dingalapadum
  • 2,077
  • 2
  • 21
  • 31