Search code examples
javac++function-callspass-by-referencecall-by-value

Call-By-Value vs Call-By-Reference revisited


let me first say. I know the title suspects that I'm asking a question which was answered here and around the internet many times. I did research indeed yet I just can't find a satisfying answer.

My question in the end comes down to this. Why is Java Call By Value and C++ Call By Reference (when using pointers) ?

Consider a method call in Java when passing references and in c++ when passing pointers. In the end in both cases I am able to make changes which are visible to the caller. Also in both cases I'm passing the address of the object to the function. In fact I'm copying i.e. making a call by value in c++ too when passing a pointer don't I?

You can simply verify that circumstance by running the following code:

#include <iostream>

void modify (int *i) {
    int a = 5;
    i = &a;
}

int main () {
    int b;
    int *i = &b;
    std::cout << i << std::endl;
    modify(i);
    std::cout << i << std::endl;
    return 0;
}

Which will print two times the same address.

For me it's just not enough to justify a call by reference with the property that you can do a swap function with it. I would like to know the very heart of what makes call by reference call by reference.

Thank you in advance.


Solution

  • My question in the end comes down to this. Why is Java Call By Value and C++ Call By Reference (when using pointers) ?

    C++ is really call-by-value, not call-by-reference. The by-reference behavior you see in C++ is a side effect of the fact that you're passing a pointer: the pointer itself is copied by value. You can't compare these situations because Java doesn't have pointers.