0

I'm a student studying Computer Science and have been instructed in lecture that we shouldn't pass a class or struct by value and should only pass them by reference. Is this true? If so I'm curious to know why.

ndubs18
  • 11
  • 2

3 Answers3

1

Passing by value involves making a copy of the object being passed. Passing by reference does not create a copy.

Whether a class or structure object should "only" be passed by reference is debatable. It depends on how the passed object is to be used.

jkb
  • 2,376
  • 1
  • 9
  • 12
0

This question has already been answered, as can be seen here:

What's the difference between passing by reference vs. passing by value?

I'd be surprised if your professor didn't go into detail about why you would pass by reference over value. This is a pretty helpful visualization of WHAT the difference is between the two:

Pass By Value vs Pass By Reference

Passing by value copies the value of an object to a new location in memory, while passing by reference is essentially the same as passing along a pointer to the original object.

Based on that, it should (but may not) be clear as to what the advantages of passing by reference over value can be. Passing by reference saves you the overhead of having to unnecessarily copy entire classes or structs.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Danny
  • 354
  • 3
  • 13
0

I don't think this statement is correct in regards to C++, unless your class objects are too large which can cause performance issues. For example, many times std::vector and std::string objects of STL library are passed, as well as returned by value.

  • But what is the advantage of passing an object by value? – Scott Hutchinson Dec 12 '19 at 04:58
  • 1
    Passing by value is preferred when you don't want any side effects to your object, i.e the object should not be changed or altered by the called function, which is preferred highly in multithreaded applications because we don't want one thread to alter data of all threads. Also, it can be efficient if your object is small in memory. – Vaibhav Thakkar Dec 12 '19 at 05:07