Pass-by-reference in C++ and java

- pass-by-reference and pass-by-pointer in C++

Refer to this
Reference is An alias (an alternate name) for an object. In following sample(swap(int& x, int& y), x is a — not a pointer to a, nor a copy of a, but a itself. Anything you do to a gets done to a, and vice versa.

Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside.

sample code:

#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
    int z = *x;
    *x=*y;
    *y=z;
}
void swap(int& x, int& y)
{
    int z = x;
    x=y;
    y=z;
}

int main()
{
    int a = 45;
    int b = 35;
    cout<<"Before Swap\n";
    cout<<"a="<<a<<" b="<<b<<"\n";

    swap(&a,&b);
    cout<<"After Swap with pass by pointer\n";
    cout<<"a="<<a<<" b="<<b<<"\n";

    swap(a,b);
    cout<<"After Swap with pass by reference\n";
    cout<<"a="<<a<<" b="<<b<<"\n";
}

Output:

Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45

After Swap with pass by reference
a=45 b=35
  • pass-by-value of the reference in java

Refer to this blog
Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value. In other words, java is more like passing the const pointer of the object.

Sample 1:

public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);
    if( aDog.getName().equals("Max") ){ //true
        System.out.println( "Java passes by value." );
    }else if( aDog.getName().equals("Fifi") ){
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
  d.getName().equals("Max"); // true
  d = new Dog("Fifi");
  d.getName().equals("Fifi"); // true
}

In this example aDog.getName() will still return “Max”. The value aDog within main is not overwritten in the function foo with the Dog “Fifi” as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return “Fifi” after the call to foo.

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

public void foo(Dog d) {
  d.getName().equals("Max"); // true
  d.setName("Fifi");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值