Lesson 45 of 45 · C++
Lesson 9: Parameter Passing – By Value and By Reference
Duration: 9 min
Lesson 45 of 45 · C++
Duration: 9 min
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.\n\n---\n\n## Example: Demonstrating Copy vs Reference\ncpp\nstruct Widget {\n Widget() { std::cout << \"Widget constructed\\n\"; }\n Widget(const Widget&) { std::cout << \"Widget copied\\n\"; }\n ~Widget() { std::cout << \"Widget destroyed\\n\"; }\n};\n\nvoid byValue(Widget w) {\n std::cout << \"Inside byValue\\n\";\n}\n\nvoid byRef(Widget& w) {\n std::cout << \"Inside byRef\\n\";\n}\n\nint main() {\n Widget w;\n byValue(w); // copy occurs\n byRef(w); // no copy\n return 0;\n}\n\n\nOutput clarifies when the copy constructor runs. For large objects, prefer pass‑by‑reference to avoid expensive copies.\n\n> Tip: Use std::move to transfer resources when you intentionally want to move from a value.\n\n---\n\n