There are two ways to pass value or data to function in C++ language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.
In C++, variables of both primitive and object data types are by default passed by value. It means only a copy of the value or object is passed to the function. So, changing the parameter in any way will not affect the original value, and passing a large object will be very slow.
In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().
Let's try to understand the concept of call by value in C++ language by the example given below:
#include <iostream> using namespace std; void change(int data); int main() { int data = 3; change(data); cout << "Value of the data is: " << data<< endl; return 0; } void change(int data) { data = 5; }
#include <iostream> #include <string> using namespace std; void change(int i) { i = 10; } void change(string s) { s = "Hello World"; } int main() { int x = 0; // value type change(x); // value is passed cout << x; // 0 string y = ""; // reference type change(y); // object copy is passed cout << y; // "" }