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)

Hmm, did you try actually setting the data member in your second constructor?

Ah, I didn't realize that it needed to be initialized manually, I thought the compiler would pick it up ... but now that I think about it, even though it was named the same, it's a different instance of the class, so it doesn't matter, it needs to be initialized in the constructor. Thanks!
So just to be clear to anyone else that reads this, I changed
MyClass::MyClass(int variable){} in the above to

MyClass::MyClass(int passed) {
	variable = passed;
	cout << "MyClass.variable = " << variable << "  @address: " << &variable << endl;
}

... it cleared things up nicely
Thanks alot, um +rep ... kinda pointless though (a bajillion + 1 ~= a bajillion)
Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.