Lesson 9 of 45
C++Lesson 9: Parameter Passing – By Value and By Reference
9 min
Course progress20%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 9 of 45
C++9 min
Keep these ideas in mind as you work through the lesson.
Understanding how arguments are passed influences performance and semantics. By value copies the argument, invoking copy constructors for class types. By reference (T&), the function works directly with the original object, avoiding a copy. Adding const to a reference (const T&) allows read‑only access without copying.
struct Widget {
Widget() { std::cout << \"Widget constructed\
\"; }
Widget(const Widget&) { std::cout << \"Widget copied\
\"; }
~Widget() { std::cout << \"Widget destroyed\
\"; }
};
void byValue(Widget w) {
std::cout << \"Inside byValue\
\";
}
void byRef(Widget& w) {
std::cout << \"Inside byRef\
\";
}
int main() {
Widget w;
byValue(w); // copy occurs
byRef(w); // no copy
return 0;
}
Output clarifies when the copy constructor runs. For large objects, prefer pass‑by‑reference to avoid expensive copies.
Tip: Use
std::moveto transfer resources when you intentionally want to move from a value.