Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens in memory when a C++ class is instantiated

Tags:

c++

memory

I'm interested in the nuts and boltw of C++ and I wondered what actually changes when an object is instantiated. I'm particularly interested if the functions are then added to memory, if they are there from runtime or if they are never stored in memory at all.

If anyone could direct me to a good site on some of the core bolts of C and C++, I'd love that too.

Thanks, Jo

like image 857
Jo Bucher Avatar asked Apr 27 '10 00:04

Jo Bucher


1 Answers

Not sure of a good web site, but Inside The C++ Object Model is a pretty good book.

At least in the usual case, the member functions exist completely independent of any instance of the class. Instead, an instance of the class is a struct containing the (non-static) data members of the object. If the class has at least on virtual function, the object will also contain a pointer to a vtable, which is basically an array of pointers to functions.

When a member function is called, the address of that object is passed as a hidden parameter to the function (many compilers reserve a register just for it) and in the function it's referred to as this.

like image 106
Jerry Coffin Avatar answered Nov 14 '22 22:11

Jerry Coffin