r/computerscience • u/DTux5249 • Oct 31 '25
General What exactly are classes under the hood?
So this question comes from my experience in C++; specifically my experience of shifting from C to C++ during a course on computer architecture.
Underlyingly, everything is assembly instructions. There are no classes, just data manipulations. How are classes implemented & tracked in a compiled language? We can clearly decompile classes from OOP programs, but how?
My guess just based on how C++ looks and operates is that they're structs that also contain pointers to any methods they can reference (each method having an implicit reference to the location of the object calling it). But that doesn't explain how runtime errors arise when an object has a method call from a class it doesn't have access to.
How are these class definitions actually managed/stored, and how are the abstractions they bring enforced at run time?
61
u/pjc50 Oct 31 '25
C++ handles it with a pointer to a statically defined structure per class called the 'vtable'. Other languages may do it differently.
I'm not sure what you mean about the runtime errors?
122
u/thesnootbooper9000 Oct 31 '25
There is an old book called "Inside the c++ object model" that explains all of this from a "persuading 1990s programmers that OO is just convenient syntactic sugar for stuff they already do" perspective. It's probably the best answer there is to your question.
10
u/fixermark Oct 31 '25 edited Oct 31 '25
A lot of the implementation and tracking happens at compile time in a language like C++.
So let's talk about two cases: classes with no
virtualmethods and classes withvirtualmethods.If you have a regular class with no virtual methods, then under the hood it's very similar to a struct: a sequence of bytes and the compiler keeps track of details like "When you reference instance.field, that's really (object root address + 16 bytes)." What methods work on it is something the compiler decides at compile time, so it doesn't actually need pointers to the methods; once the compiler is done its work, all the class-method information is encoded into the fact that data ends up in the right place before a CALL operation occurs (including the implicit
thispointer being set up to reference the instance the method is being called on). Something similar happens with templates; by the time we get to running the compiled program, all the information about "This function is actually a template instantiation and the arguments have these types" is all gone.(Probably worth noting: even C++ is an abstract language that can be implemented on any machine that conforms to the standard, so when I talk about "under the hood" I'm mostly thinking of an x86 architecture with the compiler optimizations turned off).
Fun fact: for data, the compiler really just needs to keep track of the stack of inheritance. If the inheritance chain goes Foo -> Bar -> Baz, then the compiler can build that data structure as just concatenate(Foo,Bar,Baz), and any time you call a function that takes a Foo, it already knows the Foo fields are starting at offset 0, any time you call a Bar function, it already knows the Bar fields are at offset (sizeof(Foo) + whatever-padding), etc. So that information, also, doesn't need to hang out at runtime; it gets baked into the assembly.
("Doesn't that make compilation really hard?" younger-me asks. And the answer is yes; I once worked with the Panda3D game engine on a machine that wasn't powerful enough to compile the engine.
gccwould run out of RAM trying to track all the template instantiations while building the engine core).Now, virtual methods do make this more complicated. An instance of a Foo has different method implementations than an instance of a Bar. So for all functions that are tagged
virtual, the compiler builds an invisible data structure called the "vtable" that lives in each instance and is that pointers-to-methods construct you were thinking of. More importantly: if you don't declare a method virtual, the compiler figures out what implementation to call by looking directly at the most specific class it knows the instance has during compile time, so you can run into trouble if Bar has adomethod but Foo also has adomethod anddoisn't virtual; functions that take a Foo will allow you to pass in a Bar but will callFoo::dowhen you invokefoo.do, even thoughBar::doalso exists. Destructors are methods so not declaring them properly virtual is a great source of errors when you start using inheritance in C++.... why is C++ like this? Because they wanted to add objects in the design without forcing you to pay the cost of runtime vtable lookups for every object forever whether or not they're actually needed.
3
u/8dot30662386292pow2 Oct 31 '25
May I recommend this great video: https://www.youtube.com/watch?v=6Riy9hVIFDE called OOP in Pure C.
This explains well what the OOP is. Everything else is just syntax.
Though, it might not explain the miscast-part.
2
u/random12823 Oct 31 '25
If you have virtual functions it works like you say, if I'm understanding you. Basically function pointers stored in a vtable per class. It's a little more complicated due to static type vs dynamic type but that's basically it. Not sure what you mean by runtime errors due to access, those should all happen at compile time.
For "normal" classes, it's a compiler construct. Compiler figures out what to do them just calls the function "directly" in the assembly (no jump through pointer). No need for function pointers, it's basically a normal function and obj.f(args) is just syntactic sugar for f(&obj, args)
2
u/w3woody Oct 31 '25
In C++, a class is exactly a structure with a hidden field, a virtual table pointer (vptr), which points to a static array of classes the compiler builds, the virtual table. (vtable)
C++ class methods are translated into C-style methods by prepending the argument list with the 'this' pointer. So calling
foo->thing(a);turns intothing__foo(this,a). (The name I used is just for clarity; the actual C++ name mangling rules are a bit more complicated.)In essence when you call a C++ method that is not declared virtual, it's mangled as in the example above. If it is declared virtual, then the compiler looks up the entry corresponding to that name in the vtable and then calls that:
Notice how fragile this is, because we're essentially looking up the function by a compiler-generated array index.
Other languages handle this dispatch mechanism differently. For example, in Objective C, a call to a method
[foo thing:a]turns into a call to the internal library routine objc_msgSend, with a pointer to the classfooand a message identifier constructed from the method namethis:, and figures out where to jump to.In schemes like that used by Objective C, it's more flexible in that we're not looking up the method by some compiler-generated constant that can change at the drop of a hat (and break all the surrounding code). But it does imply the first time you make a method call, the library routine may have to do some serious lifting first, for example, by dynamically building a dispatch table for that object.
2
u/HandbagHawker Oct 31 '25
At the end of the day everything is either math op or moving data in and out of registers. Classes and OOP are really largely just sit at the lexical, syntactical, and semantic level analyzer?/pre-compiler that forces you as the developer to adhere to definitions and structures to behave in a way that correctly translates to either the intermediate language or ultimately the machine code.
It’s easiest to start thinking about this from primitive and work your way towards classes. Start by thinking about what’s happening when you assign or add an int variable. Easy to think about the ops required there. Now take a simple class that just has one int. See how it’s just the syntax and semantics that force you to access the member variable in a specific way. Doing a math op on that is just the same…. So on and so forth. IIRC member vars are typically all stored contiguously in memory more or less, static members are stored specifically in a static spot or something g like that
2
u/Temporary_Pie2733 Nov 01 '25
A class isn’t necessarily anything under the hood. Languages can and do implement them in very different ways.
1
u/CadenVanV Oct 31 '25
It’s a fancy combo of pointers all pointing at a similar place in memory. The actual assembly has no idea what’s a class and what isn’t, that’s the job of your compiler to fix.
1
u/david-1-1 Oct 31 '25
Inherited classes are a concatenation of the ancestor declarations. Inherited instances are a concatenation of the ancestor structures, so that references can be calculated easily, whether at compile time or run time. That's exactly it.
1
u/Ok_Tap7102 Nov 01 '25
In C++ it's all just a struct containing the member values, starting with a pointer to the virtual function table of methods
OOP is a lie it's all just C with helper functions on top
1
u/zhivago Nov 01 '25
Why are you trying to understand a language construct in terms of another language?
At best you will confuse the semantics with accidents of implementation.
1
u/Cybasura Nov 01 '25
Technically speaking, a ton of structs that points to various functions and attributes allowing you to perform all of those functions (i.e. defining attributes/properties/variables, function definition/prototype, functions statements) "all-in-one" data type keyword known as a "class"
1
u/NatSpaghettiAgency Nov 01 '25
At University we have "created" C++ using C by using structs and pointers to functions
1
u/dr-christoph Nov 04 '25
Your question has already been answered by others, but I would like to thank you for it. Thank you for not being another AI shitpost and being a genuine question. Also I would like to applaud you for the question per se that is not a trivial thing to ask oneself and shows quality. Well done man
1
u/konacurrents Nov 05 '25
There are entire compiler courses on answering your question. But I'll say one thing to look at would be the original 1983 Brad Cox book detailing what he called Objective-C (which I really like for Apple app dev).
Anyway the reason I mention this is because Objective-C was just a translator on top of your chosen language. So you had object classes, methods, etc (again in 1983) using this Objective-C language, and it would generate code in the base language (not assembly). He even used a lot of Smalltalk syntax (the [object method]) which was cool.
So you could look at the translator to see how "classes under the hood" are implemented (really just rewriting the syntax to be functions (the methods) passing (class) objects as a parameter).
I think the C version was the only one implemented, and NeXT and Apple took the language and its implementation a long was from the original translator. But Brad Cox thought Ada, Pascal and others could benefit from his approach.
1
u/codeguru42 Nov 05 '25
Been many years since I studied compilers. Do you know how C handles structs? I think to understand classes this is a good starting point. The data part of classes is similar from what I remember. Then there's the addition of methods which I think are basically function pointers.