I tried to access a data member by a pointer, so I write this code:
#include <iostream>
#include <string>
using namespace std;
class test{
public:
int * returnAdd();
int getA();
void setmember(int x);
private:
int a;
};
int *test::returnAdd()
{
return &a;
}
int test::getA()
{
return a;
}
void test::setmember(int x)
{
a = x;
return;
}
int main(void)
{
test test1;
int *a = test1.returnAdd();
test1.setmember(12);
*a++;
cout << test1.getA() << endl;
cout << *a << endl;
return 0;
}
I expect that the value of data member (a) would become 13 but it doesn't happen. then I printed the value of *a, and I was garbage. I wonder why the value of the data member doesn't change, while a is pointing to its location?? and why *a contains garbage and not even a copy of the value of data member a???