Question

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.

Was it helpful?

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.

OTHER TIPS

The example you give is inappropriate use of call by reference. In the function modify

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

You declare a local variable a which is on the stack. When it goes out of scope, its address is meaningless. So assigning address of a to i has no effect on what i points to.

So what makes call by reference work is you can modify the value of what i points to in the function. For example:

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

Therefore in the main function, you can call it like:

int b = 2;
int *i = &b;
std::cout << *i << std::endl;  //This will print 2
modify(i);
std::cout << *i << std::endl;  //This will prints 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top