ProgrammingC++ Backend Developer

How is the inheritance of parameter passing methods in C++ (pass by value, by pointer, by reference) structured and what are the pitfalls of each method?

Pass interviews with Hintsage AI assistant

Answer.

In C++, function parameters (including method members) can be passed:

  • By value: a copy of the object is created inside the function. The original is not changed, but if there are dynamic resources, incorrect copying may occur!
  • By pointer: the address is passed. The original can be modified, but there can be nullptr, and risks due to lack of checks and memory ownership.
  • By reference: like by pointer, but the syntax is like a regular variable. The reference must be valid, cannot be redirected, but with const reduces the overhead of copying.

Example:

void foo(int value); // by value void foo(int* ptr); // by pointer void foo(const int& ref); // by reference (optimal for large objects!)

When passing by reference, optimization (copy elision) can be implemented, and for large objects, const & is recommended. For pointers, always check for nullptr.

Tricky question.

What is the difference between const MyClass& obj and MyClass obj in function parameters?

Answer:

const MyClass& does not copy the object, but only provides access without the ability to modify (optimal for large objects). MyClass obj always makes a copy, which is expensive for large sizes or when proper copying is not implemented (e.g., deep copy is not realized).

void process(const std::string& s); // Does not copy void process(std::string s); // Copies

Examples of real errors due to ignorance of the subtleties of the topic.


Story In a corporate mathematical structures library, a programmer decided to speed up work by passing large containers by value. This caused significant overhead with each function call — performance decreased by half.


Story In the user management module, pointers were used without checking for nullptr. Occasionally, random crashes occurred when accessing invalid pointers, debugging took months.


Story In an image processing project, some functions accepted objects by value, while others by reference. For one of the classes, deep copy was not implemented, causing memory leaks and implicit shared ownership of resources after passing by value.