danger/u/
This thread is permanently archived
How do I OOP

| I still can't wrap my head around classes, be it in C++, C# or Python. Like, in what cases do I know I have to use a class? What do I pass to the class? Etc.
I barely even use functions in my code. It's just one solid block of code most of the time (even though it's generosuly interspersed with comments).
How do I teach myself to do it all properly? Is there maybe a course or a book out there?


| So imagine you need a list of thread IDs on dangeru. You might make an array of ints and use that. But what if later you needed to store their associated board?

You could have two arrays, each of the same length, and access boards[i] and ids[i] to get the two pieces of information for the thread at position i.


| You could also have an array of arrays where each of the sub-arrays has exactly two items, first item is the ID second is the board. This also helps you out later because if you have a function that needs to act on a thread, you can just pass in the relevant pair as one of the arguments.


| That's basically making an array of objects. The only difference is instead of storing pairs of two elements, accessing the board with threads[i][1] and the ID with threads[i][0], you access the board with threads[i].board and the ID with threads[i].id.


| Then you get the other advantages of OOP as well, like data validation, for example you could make it so that if you try to set the ID of a thread object to a negative number, it throws an exception instead of setting it. If you were still using pairs, "threads[i][0] = -1" would be a totally valid statement and you wouldn't be able to have that kind of automatic sanitization


| To understand OOP is to understand kbjects. Think of objects like little machines you can create and destroy. Each machine has their own functions and data. OOP is convenient because when you stop needing one machine you can just destroy it and if you needed a fresh one just create a new Machine(). Classes are just blueprints of these machines and designing a class hierarchy is another step further while data structure is a different skill entirely.


| objects* not kbjects


| Classes in C++ is "Strausup type system", not the OOP

Total number of posts: 8, last modified on: Mon Jan 1 00:00:00 1505615427

This thread is permanently archived