what does exactly happen when the destructor run?


let's say you have a very simple class;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A{
	public:
		A(){}
		~A(){}
		int GetData(){return a;}
	private:
		int a;
};

int main(){

	A myObj;
	myObj.GetData();

	return 0;
}


when the program quits, everything is destroyed. Everything was on stack, and they're all gone, out of scope etc.

but what it means exactly? the stack memory location which was holding int a, was filled with null, random data, or what?

how does the compiler tell the computer that the object no longer exists?
Last edited on
EDIT: my bad i barely read the OP lol i just skimmed it

using the new and delete keywords. When you delete the object its detructor is called.
Last edited on
No, that's not it at all. The OP was not talking about dynamic memory, he was talking about memory allocated on the stack (without using new/delete).

What happens is the system interprets the machine code and through all the different layers of hardware <-> OS <-> software, the memory gets marked as free.
Last edited on
when the destructor is called, as well as the member data, the object code is removed from memory, right? I mean, in computer architecture, there's that "program counter", and the object instance, which is a copied set of instructions from the class definition plus the data, is removed right?

to make it clearer; the question, what makes an instance of a class destroyed/destructed. as far as I know, when an object is created,
1. class code is placed in memory (program stack)
2. member data is placed in memory (stack and/or heap)

if there is no other instance of this class, when a destructor of an object has called, both the code and member data is removed, the occupied memory is marked as free. right?

does that make sense to you?
Last edited on
when the destructor is called, as well as the member data, the object code is removed from memory, right?

It's marked as free memory. If you had a pointer to it you could still access it assuming that the free memory hadn't been allocated by something else.
Topic archived. No new replies allowed.