Monday, August 9, 2010

C++: its always pass by value

I was mostly a Java user for 6 years, but the last 2 years I've gone total C++. Its not that hard to follow the C++ if you understand the core programming about Java. There are minor difference here and there. Here is one of them: C++ is always pass by value, and Java is always pass by reference except for primitive objects(int, float, double, bool, char, and String, which is the most outlier from the other primitives).

Here is a sample of code (written in C++ but I guess its easy to translate in Javas term)

class Test {


 float a;


class SuperTest {

  Test test1;
  Test test2;
int main ()
 Test testObj;
 testObj.a = 10;
 SuperTest super;
 super.test1 = testObj;
 testObj.a = 30;
 super.test2 = testObj;

Here is the explanation: Test has a floating point object. SupertTest has two Test objects. In the main class, I only create one Test object named testObj. I set the value of testObj's floating point to 10. Then I set testObj as super's test1 object. After that I changed the value of the floating point to 30, and I set testObj as super's test2 object.

In Java, when I use the sign "=", it copies the REFERENCE of the object to the destination. Hence if the value of the object is changed, the value of the copied reference is also changed. So if I run those code in Java, it will print "30 30"

In C++, its all about pass by value. When you use the sign "=", its always copy the WHOLE OBJECT to a new memory, or in other term, it makes a new object with the precisely same value. When you run the program above in C++, it will print "10 30"

Probably this is why C++ use pointers (*) a lot to create a pass by reference function. Its sometimes useful and it definitely faster than copying the whole object.

No comments: