#include <bits/stdc++.h>
using namespace std;
class A{
public:
int i;
A(){
i=10;
}
void display(){
i=12;
}
void display1(){
i=13;
}
};
int main() {
stack<A>s;
A a;
A *b;
cout<<a.i<<endl;
b = &a;
b->display();
cout<<a.i<<endl;
s.push(*b);
b = &(s.top());
s.pop();
b->display1();
cout<<a.i<<endl;
return 0;
}
output :
10
12
12
expected output :
10
12
13
b is the pointer of type A and it references object a . Now we can say b is object a , whatever changes we make to b gets reflected to a. so b works like a temporary variable if there are more than one objects. when I call display() through b then variable i of object a changes from 10 to 12 and now a.i is 12 . when next time I pop from stack does the address of object a is pointed by b or the stack address ?
How can I fix the address to be of object a always , so that when I call display1() values of object a changes to 13 ?