-2

If I have a structure called student so what's the difference between these

Student& refFriend;
Student* ptrFriend;
Student valFriend;
crashmstr
  • 28,043
  • 9
  • 61
  • 79
john
  • 434
  • 1
  • 9
  • 24

5 Answers5

4
  • First one is a reference type, you need to initialize it with an instance of Student. Once it refers to an instance, you cannot change it to refer to another instance. Its fixed.

  • Second one is a pointer to Student object. You can change the pointer to point to another Student object, and you can do this as many times as you want. If you use new to create a pointer to Student object, you must have to use delete to deallocate the memory once you're done with the object, or else your program would be leaking memory.

  • Third one is an automatic object. The object will get destroyed when it goes out of scope.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

This is an extremely basic question. I would suggest finding an introductory tutorial on C++ and reading about variables, pointers (Student*), and references (Student&).

mwd
  • 420
  • 3
  • 12
2

Student& refFriend;

This is called a reference to object Student.

Student* ptrFriend;

This is called a pointer to an object Student.

Student valFriend;

This is declaring object Student with variable name valFriend. It is sometimes called a stack object.

1

Check out: What are the differences between a pointer variable and a reference variable in C++?

For an in depth look at the differences between pointers and references.

Community
  • 1
  • 1
SirensOfTitan
  • 799
  • 1
  • 7
  • 19
0
Student& refFriend; //reference pointer to Student. constant pointer, assigned only once
Student* ptrFriend; //pointer to Student. this is a dynamic pointer. can be reasigned
Student valFriend;  //instance of the Student class
Ioan Paul Pirau
  • 2,733
  • 2
  • 23
  • 26