pass by reference VS. pass by value: Which One Should You Use in Your Code?
Two ways to save data in programming
When you put data into the variable, the programming language has 2 choices to save the data.
Save data into heap memory and then keep the address of the memory in the stack memory.
save data into stack memory.
Why there are two ways?
Stack memory is much faster than heap memory. However, the stack memory has limited space. Thus, a computer is designed to save static data(temporary use, calculate damage when you hit monsters) in stack memory and save dynamic data(use again, you learn a new skill in the game.) in heap memory.
What is pass-by-value
When using the method, pass the value only. Thus, if the input data changes, the original variable’s data will not change.
Save data into stack memory.
What is pass-by-reference
When using the method, pass the value’s address. Thus, if the input data changes, the original variable’s data will be changed.
Save data into heap memory and then keep the address of the memory in the stack memory.
Java Vs. C++
Java is pass-by-value
However, when using the object, the object address will be used in the method. In other words, the original variable’s data will be changed.
public class Main {
public static void main(String[] args) {
int a = 10;
System.out.println("A is " + a); // 10
increaseNum(a);//pass the value only
System.out.println("A is " + a); // 10
Student A = new Student(24);
System.out.println(A.getAge()); // 24
increaseAge(A);// pass the object address
System.out.println(A.getAge()); // 34
}
public static void increaseNum(int input) {
int temp = input;
temp++;
}
public static void increaseAge(Student input) {
input.setAge(input.getAge() + 10);
}
}
public class Student {
int age;
public Student(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Pass-by-Value vs Pass-by-Reference in C++
C++ allows programmers to choose between pass-by-value and pass-by-reference when passing variables to functions or methods, giving them greater flexibility and control over how their programs handle data.
#include <iostream>
using namespace std;
class Student {
private:
int age;
public:
void setAge(int s) {
age = s;
}
int getAge() {
return age;
}
};
void increaseAge(Student i) {
i.setAge(i.getAge()+10);
}
void increaseAge2(Student &i) {
i.setAge(i.getAge()+10);
}
void increaseNum(int i) {
i++;
}
void increaseNum2(int &i) {
i++;
}
int main(void) {
int a = 10;
cout << "A is " << a << endl; // 10
increaseNum(a); //pass the value
cout << "A is " << a << endl; // 10
increaseNum2(a); //pass by reference
cout << "A is " << a << endl; // 11
Student B;
B.setAge(20);
cout << B.getAge() << "\\n"; // 20
increaseAge(B); //pass the value
cout << B.getAge() << "\\n"; // 20
increaseAge2(B); //pass by reference
cout << B.getAge() << "\\n"; // 30
return 0;
}