I am currently taking a C++ class which is neat since I have never taken a C/C++ class before so most of the things are fairly new.
Yesterday, we were talking about Objects. He told me if you assign one object to another you get an "exact copy" which is exactly the opposite of what my Java teacher told me saying "all objects are references and by assigning one to the other the value is a reference so you get one object with two pointers". I quickly woke up when he said that and I asked him about it he said it was a copy not just a pointer unless you specifically assign it as a pointer putting the ampersand infront of the variable name.
So I don't have Java Eclipse installed after the reformat but I have access to PHP and C++ so I tested them both.
PHP Code:
<?PHP
class dataCloset {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name];
}
public function showall() {
print_r($this->data);
}
}
$one = new dataCloset();
$two = new dataCloset();
//$three not defined
$one->b = "Hello World";
$two = $three = $one;
$one->showall();
$two->showall();
$three->showall();
$two->a = "I Rule the world";
$three->c = "I iz hungry";
$one->showall();
$two->showall();
$three->showall();
?>
Output:Output: Array ( [b] => Hello World ) Array ( [b] => Hello World ) Array ( [b] => Hello World ) Array ( [b] => Hello World [a] => I Rule the world [c] => I iz hungry ) Array ( [b] => Hello World [a] => I Rule the world [c] => I iz hungry ) Array ( [b] => Hello World [a] => I Rule the world [c] => I iz hungry )
C++ Code:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class dataCloset {
private:
int temp;
int data[5];
int at;
public:
dataCloset() {
this->at = 0;
for(temp = 0;temp<5;temp++) {
data[temp] = -1;
}
}
void set(int value) {
data[this->at] = value;
at++;
}
int operator=(int name) {
data[at] = name;
at++;
return name;
}
void showall() {
for(temp = 0;temp<5;temp++) {
cout << temp << " => " << data[temp] << endl;
}
}
};
int main(int argc, char *argv[]) {
int temp = 0;
dataCloset one;
one.set(19);
one.set(21);
one.set(20);
dataCloset &three = one, &two = one;
one.showall();
two.showall();
three.showall();
three.set(34);
cout << "\n----------\n" << endl;
one.showall();
two.showall();
three.showall();
cin >> temp;
return 1;
}
Output:0 => 19 1 => 21 2 => 20 3 => -1 4 => -1 0 => 19 1 => 21 2 => 20 3 => -1 4 => -1 0 => 19 1 => 21 2 => 20 3 => -1 4 => -1 ---------- 0 => 19 1 => 21 2 => 20 3 => 34 4 => -1 0 => 19 1 => 21 2 => 20 3 => 34 4 => -1 0 => 19 1 => 21 2 => 20 3 => 34 4 => -1
Which I thought was weird, I never realized this would be "language dependent" and it is? What's up with this?


Sign In
Create Account



Back to top









