Hi all,
Ok, so I obviously have an issue with how I'm thinking about accessor methods.
In the following code, why are the printed out values equal?
MyClass.h:
#ifndef MYCLASS_H_
#define MYCLASS_H_
using namespace std;
class MyClass {
friend ostream &operator<< (ostream &stream,MyClass const &rhs);
public:
MyClass();
MyClass(int);
MyClass(MyClass&);
~MyClass();
int getVariable();
private:
int variable;
};
#endif /* MYCLASS_H_ */
MyClass.cpp
MyClass::MyClass():variable(5) {}
MyClass::MyClass(int variable) {
cout << "MyClass.variable = " << variable << " @address: " << &variable << endl;
}
MyClass::MyClass(MyClass &Copy):variable(Copy.variable) {}
MyClass::~MyClass() {}
int MyClass::getVariable() {return variable;}
ostream &operator<< (ostream &stream,MyClass const &rhs) {
cout << "rhs.variable = " << rhs.variable << " @address: " << &rhs.variable << endl;
return stream;
}
main.cpp
#include <iostream>
#include <stdlib.h>
#include "./MyClass.h"
#include "./MyClass.cpp"
int main(void) {
MyClass C1(1);
cout << C1 << endl;
return 0;
}
So upon compilation and the subsequent executionm I get:
me@Me:~/workspace/myClass$ g++ main.cpp
me@Me:~/workspace/myClass$ ./a.out
MyClass.variable = 1 @address: 0xbfc2c0e4
rhs.variable = -1077755608 @address: 0xbfc2c108
Why does the passed MyClass no longer have the same 'variable' instance?
I've tried using a MyClass::getVariable(){} method, but it returns the same junk values. I also tried changing the overloaded operator<< to PBV instead of the PBR version above, but that _really_ doesn't work.
Any ideas?
BTW: I'm using gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12)