Java in the eyes of a C++ developer (V) – argument passing

In C++, when a function takes an argument, there are three ways of passing an argument: passing by copy, passing by reference, and passing by pointer;The programmer may select the scheme at their choice. Java supports only the first two schemes with slightly different effects, and use of a scheme is tied to the type of the argument; if the argument is a primitive datum, passing by copy is implied; otherwise, passing by reference is assumed. Let’s see some examples here

  • Passing by copy in C++

void swap(CBase a, CBase b)

{

CBase c = a;

a = b;

b = a;

}

This function has no effect on values of a and b.

  • Passing by reference in C++

void swap(CBase &a, CBase &b)

{

CBase c = a;

a = b;

b = c;

}

On return, values of a and b are swapped.

  • Passing by copy in Java

void swap(int a, int b)

{

int c = a;

a = b;

b = a;

}

This function has no effect on values of a and b;

  • Passing by reference in Java

void swap(CBase a, Cbase b)

{

CBase c = a;

a = b;

b = c;

}

This function has no effect on values of a and b.

2 thoughts on “Java in the eyes of a C++ developer (V) – argument passing”

Leave a comment