Explain the parameter passing mechanism in C++ with suitable example.


Q.) Explain the parameter passing mechanism in C++ with suitable example.

Subject: object oriented programming

Parameter passing mechanisms are used in C++ to transfer data between the calling function and the called function. There are two main parameter-passing mechanisms in C++:

  1. Pass by Value: In pass by value, a copy of the actual argument is passed to the function. Changes made to the copy of the argument in the called function do not affect the original argument in the calling function.

Syntax:

   void function(int a) {
       // Operations on the copy of 'a'
   }

   int main() {
       int a = 10;
       function(a);
       // 'a' in main() still has the value 10
   }
  1. Pass by Reference: In pass by reference, a reference to the actual argument is passed to the function. Any changes made to the reference in the called function are reflected in the original argument in the calling function.

Syntax:

   void function(int& a) {
       // Operations on the reference to 'a'
   }

   int main() {
       int a = 10;
       function(a);
       // 'a' in main() is now 20
   }

Example:

#include 
using namespace std;

// Pass by value
void passByValue(int a) {
    a++;
    cout << "Value of 'a' inside function (pass by value): " << a << endl;
}

// Pass by reference
void passByReference(int& a) {
    a++;
    cout << "Value of 'a' inside function (pass by reference): " << a << endl;
}

int main() {
    int a = 10;

    cout << "Value of 'a' before calling function (pass by value): " << a << endl;
    passByValue(a);
    cout << "Value of 'a' after calling function (pass by value): " << a << endl;

    cout << "Value of 'a' before calling function (pass by reference): " << a << endl;
    passByReference(a);
    cout << "Value of 'a' after calling function (pass by reference): " << a << endl;

    return 0;
}

Output:

Value of 'a' before calling function (pass by value): 10
Value of 'a' inside function (pass by value): 11
Value of 'a' after calling function (pass by value): 10
Value of 'a' before calling function (pass by reference): 10
Value of 'a' inside function (pass by reference): 11
Value of 'a' after calling function (pass by reference): 11

In the example above, the variable a is passed by value to the passByValue function. Changes made to the copy of a in the passByValue function do not affect the original variable a in the main function.

On the other hand, the variable a is passed by reference to the passByReference function. Changes made to the reference to a in the passByReference function are reflected in the original variable a in the main function.