i don't understand, why the pointer front is pointing on the object berta (i know that anton and berta are created on the stack)
1 Hello* front;
2
3 void createHello() {
4 Hello anton("Anton");
5 front = &anton;
6 }
7
8 int main() {
9 createHello();
10 Hello berta("Berta");
11 front->body();
12}
1 class Hello {
2 Hello(const char* name) : name(name) {
3 out.print(name);
4 out.print(" ctor;");
5 }
6
7 ~Hello(){
8 out.print(name);
9 out.print(" dtor;");
10 }
11
12 void body () {
13 out.print(name);
14 out.print( " body;");
15 }
16
17 const char* name;
18};
Output: Anton ctor;Anton dtor;Berta ctor;Berta body;Berta dtor;
out.print() is a simple function that prints an string on the monitor
I thought that will happen:
createHello() - registers are pushed on the Stack, return-address is pushed on the Stack
Hello anton("Anton") - object will be pushed on the Stack
front = &anton; pointer points on address from anton
esp - will be set to a position before the function call
Hello berta("Berta"); - object "berta" will be pushed on the Stack
front->body(); - prints Berta body; why the hell is this happening?
I mean the front pointer should point on different position in the Stack:
1.{lowerAddress}
anton <-front <-esp
return-address
registers
{higherAddress}
2.
anton <-front
return-address
registers
<-esp
3.
anton<-front
return-address
berta<-esp
So there should be just 2 possibilities: anton will be partly overridden or it still exists and berta is laying in a higher storage position. If anton will be partly overriden there should appear some rnd stuff for front->body. If anton will not be overriden then it should return "Anton body;".
Can you explain to me why that isn't happening? And instead berta overrides the object anton so that front points exactly on berta?
@Edit forgot *, so yeah front is a pointer
@Edit i would never program sth. in such a way - my university gave me this crap - idk how to solve it - yeah i just can say "hmm berta is created exactly on anton and overrides him" but i dont understand why - normally berta should be created on a higher address.
As soon as your call to createHello()
returns, Anton goes out of scope and its destructor is called, hence your output:
Anton ctor;Anton dtor;
At this point, front
is a dangling pointer.
Then you create Berta, which is pushed onto the stack in the same location Anton used to exist at, causing front
to point at Berta.
If you used new
to allocate Anton on the heap, Anton would persist through the life of the program or until you called delete
.
Edit: As per Dale's comment, this behavior should be assumed coincidental. It would be unwise to write code that assumes Berta will always exist at the same address that Anton did.