I'm a Java programmer transitioning to C++ and need some clarification on how Java is considered "pass-by-value", rather than a "hybrid". Java's baz() behaves identically to the C++'s foo() below, which is a pass-by-reference trait.
Edit: What I'm trying to understand is why bar() and baz() are pass-by-value despite different behavior. I can't find this specific answer on the forums.
Java
public class CountKeeper {
private static void baz(CountKeeper ck) {
ck.inc();
}
public static void main(String[] args) {
CountKeeper ck = new CountKeeper();
System.out.println(ck.count()); // 0
baz(ck);
System.out.println(ck.count()); // 1
}
private int count;
private int count() {
return count;
}
private void inc() {
count++;
}
}
C++
#include <iostream>
class CountKeeper
{
public:
CountKeeper();
CountKeeper& operator++();
int count();
private:
int count_;
};
CountKeeper::CountKeeper() :
count_(0)
{}
CountKeeper& CountKeeper::operator++()
{
++count_;
return *this;
}
int CountKeeper::count()
{
return count_;
}
//pass by reference
void foo(CountKeeper& ck)
{
++ck;
}
//pass by value
void bar(CountKeeper ck)
{
++ck;
}
int main()
{
CountKeeper ck;
std::cout<<ck.count(); // 0
foo(ck);
std::cout<<ck.count(); // 1
bar(ck);
std::cout<<ck.count(); // 1
return 0;
}