2. OOP: Call by Value vs. Call by Reference

Call by Value vs. Call by Reference

0. OverView

This time we will discuss the basic concepts in C++: call by value/ reference. As we know, & is the to get the address of an object. Call by value is pass the value, while call by reference is pass the address.

1. Call by Value

A new copy is created and used inside the function. Any change of this copy will not affect the original object.

void f1(int i){ i++; }

2. Call by Reference

The original copy is used inside the function, which can have a different name. Any change inside the function will at the same time change the original object. There is only one object inside and outside the function.

void f2(int &i){ i++; }

In this situation, any attempt to change value of i will cause compile time error. i is read-only inside the function. The reason to do so is because call by value copy the object, which can be memory-wasting.

void f3(const int& i) { }

3. Complete Code:

#include<iostream> 
using namespace std;

// void: this function not return anything

/*  
    call by value:
    A new copy is created and used inside the function. Any change 
    of this copy will not affect the original object.
*/
void f1(int i){ i++; }

/*
    call by ref:
    The original copy is used inside the function, which can have a different name.
    Any change inside the function will at the same time change the original obejct.
    There is only one object inside and outside the function.
*/
void f2(int &i){ i++; }

// any attemp to change value of i will cause compile time error.
// i is read-only inside the function.
// the reason to do so is because call by value copys the object, which can be memory-wasting.
void f3(const int& i) { }

// when you pass the array, remeber to pass the size of the array.
void f4(int A[], int len){ 
    // compiler will change it into
    // f4(int * A, int size)
    // when passing an arrau to a function, it always applies call by reference
    for(int i = 0; i < len; i++ )
        A[i]++;
}

// some pass by value and same pass by ref
void f5(int a, int &b){}

int main(){

    /* Call/ Pass by values vs. Call/ Pass by reference */
    
    int a = 10;
    f1(a);
    cout << a << endl;  // 10

    f2(a);  //11
    cout << a << endl;

    // new feature, the same as:
    // int A[5] = {1, 2, 3, 4, 5};
    int A[5]  {1, 2, 3, 4, 5};
    f4(A, 5);
    for(int i = 0; i < 5; i++)  
        cout << A[i] << " ";    // 2 3 4 5 6
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值