Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 45 of 45 · C++

Lesson 9: Parameter Passing – By Value and By Reference

Duration: 9 min

Parameter Passing – By Value and By Reference\n\nUnderstanding 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.\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

Note

Never return a reference to a local variable; it will dangle after the function exits.

Previous: Lesson 8: FunctionsBack to C++ Course