Data with Class

After "test.add1();" in main, the value of a is 4, but I hope it to be 5 by using class Interger.
Please help me !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  class Interger{
private:
	int data;
public:
	Interger(int _data = 0){
		data = _data;
	}
	void add1(){
		data = data + 1;
	}
};
void main(){
	int a = 4;
	Interger test(a);
	test.add1();
	cout << a;
	system("pause");
}
Well, for that, you will have to use pointers. There's a great tutorial for them here on this site- you won't have to change much for your code to work correctly.
In case it still isn't clear...

In main you make an int called a.
You then make an Interger object and pass a into its constructor by value, thereby assigning data the value of a (4).
Doing add1() after this then increments data's value by 1.

test.data is now 5, but the local variable "a" has nothing to do with the data value in your object. The local variable a's value is unchanged.

Heh, sorry if this is poorly worded. As Ispil said, if you wanted your local variable a to now be "intertwined" with the object's data value, you'd have to use pointers.
Last edited on
Topic archived. No new replies allowed.