All Posts Tagged “C++”

C++ passes by reference, Java and Ruby don’t

I got a lot of comments for the previous article, that was explaining how Ruby passes by value, just like Java does.

I thought that showing a simple example implemented in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither Java nor Ruby passes by reference.







As you can notice, in c++ example, passing by reference, will do the swap successfully.
Java and Ruby both don’t pass by reference, instead they pass a copy of the reference, which is a value finally, and so the swap fails, as swapping the copies doesn’t swap the original passed objects.

Please note also that in Java, primitive types are passed by their values directly and no need for any kind of references copies.The same case applies for Ruby, with immediate types(int, char…).

According to the previous 2 facts, we conclude that neither Java nor Ruby passes by reference, instead, both pass by value.

I think that fact that Ruby MRI is using C means they can’t use references, and so they are using pointers, and that explains why swap fails.

I hope that the idea is clear now.