Created
March 16, 2012 14:23
-
-
Save jagbolanos/2050263 to your computer and use it in GitHub Desktop.
Java is by-value, by-reference or by-sharing? Illustrated with C++ (ENGLISH)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class MyObject { | |
public: | |
int x; | |
}; | |
void object_by_value_modify_member(MyObject o) { | |
o.x = 20; | |
} | |
void object_by_reference_modify_member(MyObject &o) { | |
o.x = 20; | |
} | |
void pointer_to_object_modify_member(MyObject *o) { | |
o->x = 20; | |
} | |
void object_by_value_assign(MyObject o) { | |
MyObject newMyObject; | |
newMyObject.x = 30; | |
o = newMyObject; | |
} | |
void object_by_reference_assign(MyObject &o) { | |
MyObject newMyObject; | |
newMyObject.x = 30; | |
o = newMyObject; | |
} | |
void pointer_to_object_assign(MyObject *o) { | |
MyObject *newMyObject = new MyObject; | |
newMyObject->x = 30; | |
o = newMyObject; | |
//Memory leak, we don't delete the old object, Java would take care using GC | |
} | |
using namespace std; | |
int main() { | |
MyObject object_by_value, object_by_reference; //Q1: Where does the variable live? Where does the instance live? | |
MyObject *pointer_to_object = new MyObject; //Q2: Where does the variable live? Where does the instance live? | |
object_by_value.x = 10; | |
object_by_reference.x = 10; | |
pointer_to_object->x = 10; | |
//Q3: Which of the 3 strategies is ussed by Java? | |
cout <<"ORIGINALS:"<<endl; | |
cout <<"BY VALUE: "<<object_by_value.x<<" BY REFERENCE: "<<object_by_reference.x<<" POINTER: "<<pointer_to_object->x<<endl; | |
object_by_value_modify_member(object_by_value); | |
object_by_reference_modify_member(object_by_reference); | |
pointer_to_object_modify_member(pointer_to_object); | |
cout<<"MODIFY MEMBER"<<endl; | |
cout <<"BY VALUE: "<<object_by_value.x<<" BY REFERENCE: "<<object_by_reference.x<<" POINTER: "<<pointer_to_object->x<<endl; | |
object_by_value_assign(object_by_value); | |
object_by_reference_assign(object_by_reference); | |
pointer_to_object_assign(pointer_to_object); | |
cout <<"ASSIGN"<<endl; | |
cout <<"BY VALUE: "<<object_by_value.x<<" BY REFERENCE: "<<object_by_reference.x<<" POINTER: "<<pointer_to_object->x<<endl; | |
delete pointer_to_object; | |
return 0; | |
} | |
//FOR THE LAZY | |
//ORIGINALS: | |
//BY VALUE: 10 BY REFERENCE: 10 POINTER: 10 | |
//MODIFY MEMBER | |
//BY VALUE: 10 BY REFERENCE: 20 POINTER: 20 | |
//ASSIGN | |
//BY VALUE: 10 BY REFERENCE: 30 POINTER: 20 | |
//A1: Both live on the Stack, they are indistinct | |
//A2: The variable lives on the Stack, the instance on the Heap. They are separate entities | |
//A3: The third one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment