<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kodar piece on Medium]]></title>
        <description><![CDATA[Stories by Kodar piece on Medium]]></description>
        <link>https://medium.com/@kodarpiece?source=rss-61b1dad63258------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LeLU_YG0srKbRrsDrmvanQ.png</url>
            <title>Stories by Kodar piece on Medium</title>
            <link>https://medium.com/@kodarpiece?source=rss-61b1dad63258------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:41:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kodarpiece/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Virtual Memory]]></title>
            <link>https://medium.com/@kodarpiece/virtual-memory-f0e645b1b7ce?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e645b1b7ce</guid>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 18:14:17 GMT</pubDate>
            <atom:updated>2026-07-31T18:14:17.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Virtual memory concept as glowing brain-shaped circuit board over cyberpunk city with holographic apps." src="https://cdn-images-1.medium.com/max/1024/1*IyAwUf-10kFzbtBbdgmB2Q.png" /><figcaption>Virtual memory: the illusion of infinite RAM.</figcaption></figure><p>When we say “virtual world,” our minds drift to that cyberpunk, glossy, idealized realm. It doesn’t really exist in reality, yet we know it and live it through certain technologies.</p><p>The same goes for “virtual memory.” Every computer user dreams of endless memory — the kind that lets them run every single application at the same time.</p><p>But in reality, no such thing as “infinite memory” exists. And here’s the strange paradox: we <em>can</em> run multiple apps simultaneously, even when their total size exceeds the physical RAM. How?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBU6PPHn6iBSKVUGniFU2w.png" /><figcaption>Before and after: virtual memory saves the day.</figcaption></figure><p>“Virtual Memory” — a catch-all term for several techniques developed by operating system programmers to trick the system into believing it has unlimited memory. In this article, we’ll explore what we can of these techniques. Bismillah, and may Allah bless our journey.</p><h3>First: a program doesn’t need its entire size to run.</h3><p>Take a food delivery app, for example. The main screen shows a hundred meals. You tap one to see its details in a pop-up page.</p><p>In this context, it’s clear the program doesn’t need the other 99 meal pages — it only needs the one you’re viewing. Loading all those other pages into RAM is undeniably a waste of resources. Worse, if the RAM were smaller than the app’s total size, running it would be impossible from the get-go!</p><p>That’s why the operating system loads only the pages the program actually needs at that very moment. This saves RAM space, allows multiple apps to run together, and speeds up launch times because it only pulls a few pages from the hard drive instead of the whole application.</p><h3>How is a program split into pages?</h3><p>(Forget the food delivery example now — don’t think it’s the only program that can be split, or that “page” means the pop-up screen you see while using the app.)</p><h4>During compilation and linking,</h4><p>besides translating everything into machine code, the program is divided into equal-sized pages. For the OS to successfully load only what’s needed, it must read and understand the division the compiler created.</p><p>The division is equal in size, like apple slices — literally. Imagine a program with 100 lines of code; the compiler might split it into four pages, each containing 25 lines.</p><h4>The operating system, in turn,</h4><p>divides the system’s physical memory into equal-sized chunks called frames. For instance, if the system has 1GB of RAM and each frame is 4KB, that gives us 262,144 frames.</p><p>The page size (say, 4KB) isn’t random — it’s agreed upon between hardware designers and OS developers. That’s why you won’t see a mismatch between a page and a frame.</p><p>Then, as we mentioned, the OS reads the program’s page table, matches page to frames, and stores info about all pages in a big table. After that, it picks the pages the program needs right now and loads each into a separate frame. These frames don’t have to be adjacent — they can be scattered, because the OS maintains a separate table to track exactly where each page lives.</p><h4>This table is called the Page Table Entry (PTE).</h4><p>It stores info about all the program’s pages. The OS refers to it every time it needs to deal with a particular page. It stores the page ID, which frame it’s mapped to, whether a frame has been assigned at all, whether it’s in RAM, on the hard disk, or simply unavailable.</p><h4>The whole process in a nutshell:</h4><ol><li>Program X wants to run.</li><li>The OS splits it into pages.</li><li>The OS gathers info about the pages and builds the page table.</li><li>The OS loads the pages needed right now into RAM.</li><li>The rest stay on the hard disk — but the OS has all the info it needs to load them accurately and smoothly later on.</li></ol><h3>What happens when a program needs a page that’s not in RAM?</h3><p>The OS pauses the program, then simply fetches the page from the hard disk if it’s there. If it can’t find it, the OS terminates the application for good.</p><p>This event is called a Page Fault, triggered by the CPU when it can’t locate the page in RAM, and handled by the OS.</p><h4>This process is slow because it involves a lot of overhead:</h4><p>Saving the application’s state, reading the process table, reading from the hard disk, updating the process table, and then resuming what the app was doing. That’s all wasted time, because it halts the program from doing its real job. To reduce the number of these faults, the OS employs several tricks — we’ll get to them later.</p><h3>What if RAM is completely full?</h3><p>Imagine a program needs a new page, so a Page Fault starts — but surprise! The OS finds no room; memory is entirely full. The only option left is to kick out a “victim” page and replace it with the new one.</p><p>The OS chooses the victim using various algorithms:</p><h4>The simplest: FIFO (First In First Out)</h4><p>Pick the oldest page in RAM and replace it. Very simple, but it causes more and more Page Faults, because old pages might be heavily used. When they’re evicted, whatever program uses them will trigger a new fault, and so on.</p><h4>The theoretical: Optimal Page Replacement</h4><p>Pick the page that won’t be used in the near future. But since we can’t predict the future, this algorithm stays in textbooks only. It’s considered the gold standard for comparing other algorithms.</p><h4>The practical: LRU (Least Recently Used)</h4><p>Pick the page that hasn’t been used for the longest time. The OS looks at all pages and evicts the one that’s been idle the most. This is feasible and performs better than FIFO. Example: a program repeatedly uses page (A) every 5 seconds (and it’s the oldest), while page (B) was used once a minute ago. FIFO would evict A, but LRU would evict B.</p><h4>Heads-up: in some systems,</h4><p>the victim selection isn’t global across all RAM. This strategy is called <em>Global Replacement</em>, and it allows one app to steal frames from another. While efficient, it unfairly punishes the other app, because it’ll suffer from stalls and Page Faults later on due to the memory thief.</p><p>The alternative is <em>Local Replacement</em>, where each app can only pick victims from its own frames. This has its own pros and cons compared to Global Replacement.</p><h3>Ways to speed up Page Fault handling:</h3><p>In the page table, each page has a bit called the Dirty Bit. It tells the OS whether the page has been modified or not. If it’s clean, the OS evicts it without saving its state to disk — which dramatically reduces Page Fault time.</p><p>But if it’s dirty, the OS saves its state. Here’s the neat part: the OS proactively saves dirty pages before they’re even chosen for eviction, using idle moments to do the heavy lifting in the background without slowing down the interactive interface. This also cuts down Page Fault latency.</p><h3>Frame allocation strategies:</h3><p>Different loading strategies determine how many frames each app gets initially:</p><h4>Equal Allocation:</h4><p>Every app gets the same number of frames, regardless of size or priority. This is bad because it gives small apps more than they need.</p><h4>Proportional Allocation:</h4><p>Frames are assigned proportionally to the app’s size — the larger the app, the more frames it gets. This is smarter, because each app gets what it needs without excess or deficiency.</p><h4>The fairest: Priority Allocation</h4><p>This combines the above and also considers priority. Some apps, even if small, are mission-critical and can’t tolerate delays waiting for new pages. They deserve more RAM space. It also respects size: if an app is both large and high-priority, it gets even more frames.</p><h3>The trap the OS can fall into:</h3><p>When a Page Fault happens, the affected applications stall. The OS sees the CPU sitting idle, so it adds more apps to the mix. These new apps crowd out the old ones in RAM, causing more Page Faults. More stalls follow. The OS sees even more idle CPU time, adds even more apps, and the cycle continues until the system grinds to a halt — or even crashes. This is called <em>Trashing</em>.</p><p>The OS avoids this nightmare in two ways:</p><h4>1. It kills specific applications to free up space for the remaining ones.</h4><h4>2. It applies the <em>Working-Set Model</em>:</h4><p><strong>The idea is that over a given time window</strong>, an app only works on a stable set of pages — it doesn’t jump around randomly. For instance, when you’re typing in a text editor, you spend a long time using a limited set of features. That stable set is called a <em>Locality</em>.</p><p>The OS identifies this locality using something called the <em>Delta Parameter</em> — essentially, “how far back should the OS look to determine the page range?” From the start of the app? From the middle? Or only from recent history?</p><p>Once it determines the locality, it dynamically adjusts the number of frames up or down to match that working set.</p><h3>The bottom line:</h3><p>The operating system fights a constant war to ensure every application gets exactly the right number of frames at all times — the perfect amount to keep it running smoothly without any Page Faults. And that, right there, is what makes the multitasking system we all know and use every single day possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e645b1b7ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If every app needs to be loaded into RAM to run, how can you run a 6GB app on a computer with only…]]></title>
            <link>https://medium.com/@kodarpiece/if-every-app-needs-to-be-loaded-into-ram-to-run-how-can-you-run-a-6gb-app-on-a-computer-with-only-0917916b2fd4?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/0917916b2fd4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 11:52:47 GMT</pubDate>
            <atom:updated>2026-07-15T11:52:47.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>If every app needs to be loaded into RAM to run, how can you run a 6GB app on a computer with only 4GB of RAM?</h3><figure><img alt="A tiny RAM chip struggles to hold a massive 6GB app icon, illustrating the challenge of running large applications on limited memory." src="https://cdn-images-1.medium.com/max/1024/1*jE907iRkiv794YdK4q9cjw.png" /><figcaption>cover-ram-vs-app-size</figcaption></figure><p>Imagine you have a restaurant app in your hands right now. It shows you 100 suggestions on the screen, and you can tap on a specific one to get more details about it.</p><h4>From this structure,</h4><p>we can easily conclude that the user doesn’t need the other 99 suggestions. Loading all of them into RAM isn’t just wasteful — it’s a real problem, because the app’s size exceeds the RAM’s capacity.</p><p>That’s why, in reality, the entire app isn’t loaded into the computer’s RAM. Only the parts the user will actually need at that moment are loaded, using a technique called:</p><h3><strong>Dynamic Loading</strong></h3><figure><img alt="A puzzle showing only one glowing piece loaded into RAM, representing dynamic loading technique where only needed app parts are loaded." src="https://cdn-images-1.medium.com/max/1024/1*QrTHr4cyQWUtWtfUo70NiQ.png" /><figcaption>dynamic-loading-explained</figcaption></figure><p>This technique has one sole purpose: loading only the essential parts that the user will need into RAM, while leaving the rest aside. For this to work, it requires cooperation between the operating system and the programmer.</p><h4>The programmer’s role</h4><p>Is to divide the app into units (routines) using specific code, and define the purpose of each unit and when the user will need it.</p><h4>Then comes the operating system’s role:</h4><p>It identifies these divisions, maps their boundaries, and loads them exactly when they’re actually needed.</p><h4>This way,</h4><p>we enable the user to run multiple apps at the same time, even if their total size is larger than the available RAM! This approach also makes app startup faster, because reading from the slow hard drive takes less time — since we’re not loading the entire app, just a small fraction of it.</p><h3>It also makes swapping between apps easier</h3><figure><img alt="Two portals labeled RAM and Hard Drive with a circular arrow swapping data, illustrating the swapping process between fast memory and slow storage." src="https://cdn-images-1.medium.com/max/1024/1*0D5OQwsrJXQV7zZyog_CDQ.png" /><figcaption>swapping-between-ram-and-hard-drive</figcaption></figure><p>Imagine the scheduler picks app Y to run, but app Y isn’t in RAM, and worse — RAM is completely full. Instead of the app freezing, the operating system picks a part of some app X that’s occupying RAM but is rarely or never used, evicts it from RAM, and places app Y in its place to run.</p><p>This is far better than evicting the entire app X and shutting it down completely.</p><h4>However, this swapping process is slow!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqMTM9aFY1T0H1RrPvgjew.png" /><figcaption>cpu-cycles-vs-storage-latency</figcaption></figure><p>Because every time a part of an app is evicted, its state must be saved safely to the hard drive so no information is lost, and then restored when needed again. And as we all know, mentioning the hard drive means mentioning slowness.</p><figure><img alt="Infographic showing 20MB data moving at 40MB/s to a hard drive, taking 500ms, visualizing the math behind memory swapping delays." src="https://cdn-images-1.medium.com/max/1024/1*RkPT48jCNMv1U5FMLrlj1A.png" /><figcaption>data-transfer-time-infographic</figcaption></figure><p>Let’s say the hard drive read speed is 40MB/s, and the size of the part we’re evicting from RAM is 20MB.</p><p>Doing the math, we find that we need 500 milliseconds to transfer this part from RAM to the hard drive — and this duration feels like an eternity to the processor! A 3GHz processor can execute around 1.5 billion cycles in that half-second!</p><h4>That’s why experts established a rule:</h4><figure><img alt="A robot professor explaining the expert rule: only swap a memory page if its run time exceeds the swap time, to avoid wasting processor cycles." src="https://cdn-images-1.medium.com/max/1024/1*uh8c9RrNMm8yGRR6OgzVjg.png" /></figure><p>Never evict a part of RAM unless it has been running for longer than the swapping time itself; otherwise, it would be a massive waste of time.</p><h4>Also,</h4><p>it’s forbidden to swap out a part that’s currently reading from or writing to the hard drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCkUVxJbc0K2ScYiiMZMzQ.png" /><figcaption>swap-during-io-security-risk</figcaption></figure><p>Because evicting it and placing another app in its spot means the hard drive might deliver the evicted part’s data straight to the new app! That’s a security breach, plain and simple. So interrupting any part during I/O operations is strictly prohibited.</p><h3>It’s astonishing</h3><figure><img alt="Peaceful user smiling at a laptop, with an x-ray view showing chaotic internal battles of data streams and tiny robots inside the processor, symbolizing unseen OS complexity." src="https://cdn-images-1.medium.com/max/1024/1*x78qDIWQ_SDbki6cLo4J_w.png" /><figcaption>internal-os-battles-metaphor</figcaption></figure><p><strong><em>To reflect</em></strong> on the scale of conflicts and decisions taking place inside your computer in just a few seconds — while we remain completely unaware of them, unable even to count them.</p><p>And for modern systems, what we’ve described here is nothing more than child’s play, because what’s really happening inside is actual <strong>world war-level complexity </strong>— all for our comfort and a seamless experience.</p><p>— kodar piece</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0917916b2fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does the Operating System Translate Variable Names into Real Addresses?]]></title>
            <link>https://medium.com/@kodarpiece/how-does-the-operating-system-translate-variable-names-into-real-addresses-4f40cf333b23?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f40cf333b23</guid>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 17:49:04 GMT</pubDate>
            <atom:updated>2026-07-13T17:49:04.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVXGtoNCbziuq_YC5Y-6dg.png" /><figcaption>Generated by AI</figcaption></figure><p>In every programming course, the professor will inevitably say: “Variable names are really just a fancy label for some address in RAM” — and that’s 100% true. But the more important question is: when does a variable name actually turn into a real address? And how does that transformation happen?</p><p>Let me break it down for you simply.</p><h3><strong>A Golden Rule: </strong>multiple programs, separate memory</h3><p>For any program to run, it has to be copied from the hard disk into RAM. And for multiple programs to run at the same time, each one needs its own space in memory — space no other program touches.</p><p>The operating system is the one responsible for guaranteeing this rule.</p><h3><strong>The Core Problem: </strong>Program can’t know where it’ll land</h3><p>When you write a program and say: put the number 7 into variable x, the program needs to know exactly where to write that number in memory.</p><p>But here’s the problem: the program can’t pin down the real address in advance, because it has no way of knowing beforehand where it’ll find free space in RAM once it’s loaded. If we hard-coded fixed addresses, that spot might already be occupied by another program — and the program would simply never run!</p><h3>To solve this, there are two main approaches:</h3><h4><strong>Approach One: Translation at Load Time (Static Relocation)</strong></h4><p>This approach is old, but easy to understand.</p><p>It is composed of two phases: the compile phase and the loader phase</p><p><strong><em>What does the compiler do?</em></strong></p><p>When the compiler turns your code into machine language, it doesn’t write real addresses — it writes logical (relative) addresses, like:</p><ul><li>put variable x at START + 7</li><li>put variable y at START + 12</li></ul><p>Where START means: “the beginning of the program in memory” — except we don’t know its real value yet.</p><p><strong><em>What does the Loader do?</em></strong></p><p>When the OS goes to load the program into memory, it finds an open spot — let’s say it starts at address 7000. The loader then translates every virtual address into a real one:</p><ul><li>START + 7 becomes 7007</li><li>START + 12 becomes 7012</li></ul><p><strong>This way,</strong> the program knows its real addresses before it even starts executing.</p><p><em>Drawbacks of this approach:</em></p><ul><li>Slow, since the loader has to translate every address before execution starts.</li><li>Inflexible, since once the program is loaded, it can’t move around in memory. If it exits and tries to come back, its old spot might already be taken — and it can’t relocate, because its addresses are fixed.</li></ul><p>That’s exactly why modern systems don’t use this approach.</p><h3><strong>Approach Two: Translation at Execution Time</strong></h3><p>This is the approach used by every modern operating system (Windows, Linux, Mac).</p><p><strong>The idea, in short:</strong></p><p>For its entire runtime, the program never actually knows where it really lives in memory. Only the processor and the MMU know the real address — and only in the moment, at every single point of execution.</p><p><strong><em>What is the MMU?</em></strong></p><p>Short for Memory Management Unit — a piece of hardware inside the processor whose one and only job is translating logical addresses into real ones.</p><p><strong><em>What happens when the program runs?</em></strong></p><p>When the program says: “put the number 7 at START + 8,” the processor doesn’t go straight to that memory location. Instead, the MMU steps in.</p><p>The MMU does the following:</p><ol><li>Receives the virtual address from the program (START + 8).</li><li>Looks up the program’s START.</li><li>Computes the real address.</li><li>Hands the real address to the processor.</li></ol><p>Here, the loader’s only job is to set START — it doesn’t compute real addresses itself. That job is left entirely to the MMU, which does it on the fly with every single memory access, avoiding exactly the problems we mentioned earlier.</p><p>This approach is about as complete and comprehensive as it gets — and since the MMU is part of the processor itself, it runs at blazing speed, sidestepping any performance concerns.</p><p><em>You could say the only real downside of this approach is:</em></p><p>its dependence on a specialized piece of hardware (the MMU), which older computers don’t have. But that’s not really an issue we deal with anymore, since every modern processor comes equipped with one.</p><h3>And that’s not the whole story!</h3><p>For modern systems, the “execution time” process we just described is really just a simplification. In reality — if we want to get closer to what actually happens — there isn’t just one single START! The program is split into several parts, each with its own place in RAM, and the operating system keeps track of where each part begins and ends. The MMU then locates the right part with the OS’s help — along with plenty of other fascinating details we’ll get into later!</p><p>— kodar piece</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f40cf333b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The System’s Dirty Secret: How Operating Systems Actually Deal with Deadlock]]></title>
            <link>https://medium.com/@kodarpiece/the-systems-dirty-secret-how-operating-systems-actually-deal-with-deadlock-c2cd08bd7435?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2cd08bd7435</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 13:17:35 GMT</pubDate>
            <atom:updated>2026-07-08T13:17:35.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqfnt4Lysj73bdJ8BMgbDQ.png" /><figcaption>Generated by AI</figcaption></figure><p>Deadlock is one of the most violent problems in operating systems — so violent that the system itself usually just ignores it and hopes it never happens. Like leaving the house before sunrise, quietly praying you don’t run into a rabid dog. Most operating systems are terrified of it, but they hide that fear well.</p><h3>Here’s the bitter truth:</h3><p>Everything you read about deadlock solutions in textbooks looks beautiful on paper, but falls apart in the real world.</p><p>Most of these solutions are far too expensive for the system to run, and impossible to generalize across every competing process at once. Deadlock is like an earthquake — you never know when it’ll strike, or from which direction.</p><p>That’s why most operating systems don’t take any real preventive measures. Instead, they ignore the problem, and when it does happen, they resort to one of two things:</p><ul><li>Restart the entire system,</li><li>Or kill the frozen processes.</li></ul><h3>Restarting is the obvious,</h3><p>easy fix — but it’s shallow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNQL3AGf_8w4wuSbGOjgCQ.png" /><figcaption>Generated by AI</figcaption></figure><p>It doesn’t uproot the disease; deadlock can come right back within minutes. If we wanted to compare it to something, it’s like giving an old TV, fridge, or car a good whack to get it working again — a momentary painkiller, not a cure.</p><h3>Killing the frozen processes is the more logical solution,</h3><p>even if it’s costly and slow.</p><p>Unfortunately, it’s the only real option most systems have.</p><p>This solution splits into two approaches:</p><h4>The first approach:</h4><p><strong>kill all</strong> the deadlocked processes at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqFA0JEL8-KUAoyZlYTEWg.png" /><figcaption>Generated by AI</figcaption></figure><p>This guarantees the deadlock ends, but it’s brutally expensive — like your car breaking down and, instead of fixing it, you scrap the whole thing and buy an identical replacement.</p><p>It’s worth noting that killing a process doesn’t mean banning it forever — it simply ends its current session, and it can be restarted later if the user or the system wishes.</p><h4>The second approach:</h4><p><strong>Pick a single victim and eliminate it</strong>. If the deadlock persists, pick another victim. And so on, until the crisis clears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIrwGhj25duQJwKcNCli1w.png" /><figcaption>Generated by AI</figcaption></figure><p>Here, the operating system starts acting like a shrewd, cunning politician, applying the logic of “the greater good” — sacrificing one instead of sacrificing everyone. It chooses its victim based on several indicators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AH7mxA3WhuBdLsoJD1KyDQ.png" /><figcaption>Generated by AI</figcaption></figure><ol><li><strong>Priority in the system </strong>— every process carries a number that reflects its importance. The higher the number, the more important the process; the lower, the more expendable. The system looks for the least important deadlocked process and marks it as the prime candidate for sacrifice.</li><li><strong>How close it is to finishing</strong> — this one is more theoretical, since the system can’t know for certain how long a process will take. But it can estimate whether a process is close to completion. If a process has already consumed most of the resources it needs and has little left to do, the system spares it.</li><li><strong>How many resources it’s holding</strong> — the system looks at how many resources a process monopolizes. The fewer it holds, the cheaper it is to kill, since the system won’t have to do extensive rollback work to disk. This makes it another ideal candidate for sacrifice.</li><li><strong>A touch of fairness</strong> — if the system notices a particular process keeps getting killed over and over, it starts avoiding it, giving it a chance to finally run.</li></ol><h3><strong>And that’s really all there is to it,</strong></h3><p>in the end, we discover that operating systems, too, are afraid of something. And that, much like humans, they’re lazy — they don’t like doing more work than necessary — and more than a little cunning, quick to bully the weak.</p><p>— Kodar Piece.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2cd08bd7435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Standoff Nobody Wins: Understanding Deadlock]]></title>
            <link>https://medium.com/@kodarpiece/the-standoff-nobody-wins-understanding-deadlock-7dbc6d905c4a?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dbc6d905c4a</guid>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 16:04:22 GMT</pubDate>
            <atom:updated>2026-07-06T16:04:22.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xlz7YhkycPHHpd92qsxNOg.png" /><figcaption>Generated by AI</figcaption></figure><p>Imagine you’re standing in front of a public door, trying to leave. At the exact same moment, someone else walks up wanting to leave too. They step aside to let you go first. You do the same for them. And now you’re both frozen, each waiting for the other to move.</p><p>Nobody moves. You stay like that forever.</p><p>This is exactly what happens inside a computer, and it’s called a <strong>deadlock</strong>.</p><p>Picture a file, and two processes that both want to write to it. The first is waiting for the second to finish, and the second is waiting for the first. The result? Neither writes. The processor freezes, the system slows down. If this happens with large-scale processes, the entire system can grind to a halt, forcing a restart.</p><p>To an ordinary user, this might seem like a minor annoyance. To a server handling millions of users, it’s a catastrophe — a single deadlock there can mean paralyzing a global service. That’s why deadlock is one of the most notorious problems in operating systems, and why programmers keep racing to find an algorithm that solves it once and for all. They all fail to find one complete solution. There are good solutions, but they’re full of holes. Others are weak, or rely on luck.</p><p>In theory, breaking a deadlock means breaking one of its four necessary conditions.</p><h3>1. Mutual Exclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3mR98_JQDSJUIGZaxVuPw.png" /><figcaption>Generated by AI</figcaption></figure><p>Mutual exclusion lets one process monopolize a resource until it’s done with it — like a public restroom locked from the inside. Remove the lock, and the deadlock disappears with it. But would you be okay with someone walking in on you?</p><p>Without a lock, any process can barge into the resource and grab whatever it wants, and chaos follows. Imagine a file containing “password: wxyz.” One process comes to write “hello,” another comes to read the password at the same time. The first ends up writing “wxyzhell,” and the second reads “wxyzhel” — neither one wrote or read anything correctly.</p><h3>2. Hold and Wait</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1-UJaSCuF-liQz8N35H4A.png" /><figcaption>Generated by AI</figcaption></figure><p>Process X wants files a and b. Process Y wants them too. X grabs a and waits for b. Y grabs b and waits for a. Each waits on the other, forever.</p><p>This condition can be broken by killing one of the two processes — the common fix in operating systems — but it’s costly. Killing a process means losing its work, and it takes time to recover.</p><h3>3. No Preemption</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNaUknyu6qQAVf7qBJermw.png" /><figcaption>Generated by AI</figcaption></figure><p>This means a resource, once held by a process, can’t be forcibly taken away — not even by the system itself. It’s similar to the previous condition, but it applies to resources that can’t simply be returned to their earlier state.</p><p>Take a printer: you can’t stop a print job midway and yank the paper out; the reservation is final. This is why this condition is especially hard to break for this kind of resource.</p><h3>4. Circular Wait</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5-bw-bOlsH0oWPV3uimYw.png" /><figcaption>Generated by AI</figcaption></figure><p>In our earlier example, the cycle looks like this:</p><p><strong>X → a → Y → b → X</strong></p><p>Break that circle, and you’re safe. This is, practically speaking, the easiest condition to break — for instance, by ordering resources in a fixed sequence and having processes acquire them in that order.</p><p>Say the order is [a, b]. X arrives and takes a. Y arrives and finds a already taken, so it waits without grabbing anything. No cycle forms. X finishes and releases its resources.</p><h3>These four conditions,</h3><p>and breaking them, form what’s known as deadlock <em>prevention</em>. There are other doors too: ignoring the problem entirely, detecting it and killing it after the fact, or simply restarting the system.</p><p>We’ll walk through the rest of those doors in upcoming articles.</p><p>So stay with us, dear readers.</p><p>Until next time.</p><p>— Kodar Piece.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dbc6d905c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Shots 3.5 — Parent Pointers & Child Objects (The Bridge to Polymorphism)]]></title>
            <link>https://medium.com/@kodarpiece/c-shots-3-5-parent-pointers-child-objects-the-bridge-to-polymorphism-149bd53e2526?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/149bd53e2526</guid>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 17:15:29 GMT</pubDate>
            <atom:updated>2026-06-26T17:15:29.618Z</atom:updated>
            <content:encoded><![CDATA[<p>In Shot #3, you learned how a child class inherits from a parent class.</p><p>But there is one more thing you need to know before we dive into polymorphism (Shot #4).</p><p>A parent pointer can point to a child object.</p><p>This is the bridge between inheritance and polymorphism. Let’s learn exactly how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwFHEYFH-lL_Kl8tmqbFVg.png" /></figure><h3>The Declaration</h3><pre>ParentClass* pointer = new ChildClass();</pre><p>Let’s break it down:</p><ul><li>ParentClass*A pointer that can hold an address of a ParentClass object.</li><li>pointerThe name of the pointer variable.</li><li>= Assignmentnew ChildClass()Creates a new ChildClass object in heap memory.</li><li>;End of statement.</li></ul><h3>new ChildClass()</h3><p>new ChildClass() returns a pointer (the memory address) of the newly created object.</p><pre>ChildClass* ptr = new ChildClass();<br>//                    ↑<br>//                    This returns a pointer (address)</pre><p>When you write new ChildClass(), three things happen:</p><ol><li>Memory is allocated on the heap.</li><li>The ChildClass constructor runs.</li><li>The memory address of that object is returned.</li></ol><h3>Why You Can Assign It to a Parent Pointer?</h3><p>Because a child pointer can be assigned to a parent pointer.</p><pre>ChildClass* childPtr = new ChildClass();  // Returns ChildClass*<br>ParentClass* parentPtr = childPtr;         // ✅ Allowed (upcasting)</pre><p>Or in one line:</p><pre>ParentClass* ptr = new ChildClass();  // ✅ Works</pre><p>The new returns a ChildClass*, but C++ automatically converts it to ParentClass* because of the &quot;is-a&quot; relationship.</p><h4>Why Is This Allowed?</h4><p>Because of inheritance: A child IS-A parent.</p><pre>class Animal { };<br>class Dog : public Animal { };<br><br>Animal* ptr = new Dog();  // ✅ Allowed! Dog is an Animal</pre><h4>example:</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Animal { };<br>class Dog : public Animal { };<br><br>int main() {<br>    Dog* dogPtr = new Dog();           // new returns Dog*<br>    Animal* animalPtr = new Dog();     // new returns Dog*, then converts<br>    <br>    cout &lt;&lt; &quot;Address returned by new: &quot; &lt;&lt; dogPtr &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Address in animalPtr: &quot; &lt;&lt; animalPtr &lt;&lt; endl;<br>    <br>    delete dogPtr;<br>    return 0;<br>}</pre><p><strong>output:</strong></p><pre>Address returned by new: 0x15b72e8b0<br>Address in animalPtr: 0x15b72e8b0</pre><p>Same address. Just stored in different types of pointers.</p><h3>What Can You Access Through This Pointer?</h3><p>Only the parent’s members.</p><p>The compiler only knows that ptr is an Animal*. It does not know that it actually points to a Dog.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Animal {<br>public:<br>    void speak() {<br>        cout &lt;&lt; &quot;Animal speaks&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Dog : public Animal {<br>public:<br>    void bark() {<br>        cout &lt;&lt; &quot;Dog barks&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Animal* ptr = new Dog();<br>    <br>    ptr-&gt;speak();  // ✅ Works (speak exists in Animal)<br>    // ptr-&gt;bark();  // ❌ ERROR! Animal does not have bark()<br>    <br>    delete ptr;<br>    return 0;<br>}</pre><p><strong>Output:</strong></p><pre>Animal speaks</pre><p>Even though ptr actually points to a Dog, you can only call methods that belong to Animal. The bark() method is hidden through this pointer.</p><h4>Why?</h4><p>The answer lies in how objects are arranged in memory.</p><p><strong>What does a Dog object actually look like in memory?</strong></p><pre>Dog Object Memory Layout:<br>┌──────────────────────────────┐<br>│   Animal part (parent)       │  ← First part of memory<br>│   - name                     │<br>│   - age                      │<br>│   - eat()                    │<br>│   - sleep()                  │<br>├──────────────────────────────┤<br>│   Dog part (child)           │  ← Second part of memory<br>│   - bark()                   │<br>│   - breed (if exists)        │<br>└──────────────────────────────┘</pre><p>The Dog object contains everything from Animal, PLUS its own additions.</p><p><strong>What Does the Pointer Know?</strong></p><p>A pointer is just an address (a number) pointing to a location in memory.</p><p>When you write:</p><pre>Animal* ptr = new Dog();</pre><p>The compiler creates a pointer that knows:</p><ul><li>The memory address of the object.</li><li>The type of the pointer (Animal*).</li></ul><p>The compiler does NOT know (or care) that the actual object is a Dog.</p><p>The compiler sees only the pointer type, not the actual object type.</p><pre>Animal* ptr = new Dog();<br><br>// The compiler thinks: &quot;ptr points to an Animal&quot;<br>// It does NOT know: &quot;ptr actually points to a Dog&quot;</pre><p>The address is the address of a Dog object, but the compiler does not care about this.</p><p>When you use the pointer to move through memory, the compiler will keep asking one thing: <em>“Is this an </em>Animal<em> (the pointer&#39;s type)?&quot;</em></p><ul><li>If yes → access is allowed.</li><li>If no → access is blocked.</li></ul><p>The compiler does not look at what actually exists in memory. It only looks at what matches the pointer type.</p><p><strong>Visual Example</strong></p><p>Imagine memory addresses like house addresses.</p><pre>Address 1000: ┌─────────────────┐<br>              │ Animal part     │  ← Dog object starts here (1000)<br>              │ (name, age)     │<br>Address 1100: ├─────────────────┤<br>              │ Dog part        │<br>              │ (bark, breed)   │<br>              └─────────────────┘</pre><pre>Animal* ptr = new Dog();  // ptr stores address 1000</pre><p>Now ptr points to address 1000.</p><p>The compiler knows: <em>“At address 1000, there is an Animal.”</em></p><p>It does NOT know that at address 1100 there is Dog data. It only knows about the Animal part at 1000.</p><p>When you call ptr-&gt;bark(), the compiler looks at address 1000 + offset for bark(). But there is no bark() in the Animal section. Error.</p><h3>Why Does This Matter?</h3><p>This pattern allows you to write code that works with any derived class without knowing which one.</p><p>Parent pointers let you treat different child objects as if they were the same type, so you can write one function or one loop that works with all of them.</p><p>Imagine you have three animals: a Dog, a Cat, and a Bird. You want to store them all together and make them all eat().</p><p>Without parent pointers, you need three separate arrays:</p><pre>Dog dogs[10];<br>Cat cats[10];<br>Bird birds[10];</pre><p>To make them all eat, you need three separate loops:</p><pre>for(int i = 0; i &lt; dogCount; i++) dogs[i].eat();<br>for(int i = 0; i &lt; catCount; i++) cats[i].eat();<br>for(int i = 0; i &lt; birdCount; i++) birds[i].eat();</pre><p>This is repetitive and messy. What if you have 20 types of animals? You would write 20 loops.</p><p>With parent pointers, you can store all animals in one array of Animal*:</p><pre>Animal* zoo[100];  // One array holds ALL animals<br><br>zoo[0] = new Dog();<br>zoo[1] = new Cat();<br>zoo[2] = new Bird();<br>// ... add more animals</pre><p>Now, to make every animal eat, you need only one loop:</p><pre>for(int i = 0; i &lt; animalCount; i++) {<br>    zoo[i]-&gt;eat();  // Works for Dog, Cat, Bird, everything!<br>}</pre><p>One loop. Not three. Not twenty. One.</p><p>This is the real power of parent pointers: writing code that works for any derived class without modification.</p><p>This is called polymorphism (coming in Shot #4). The magic is that zoo[i]-&gt;eat() automatically calls the correct eat() version – Dog&#39;s version, Cat&#39;s version, or Bird&#39;s version – depending on what the pointer actually points to.</p><h3>Another Thing</h3><p>Do not forget to delete the memory or you will get a memory leak:</p><pre>// After the loop, clean up<br>for(int i = 0; i &lt; animalCount; i++) {<br>    delete zoo[i];<br>}</pre><h3>A Note on Destructors</h3><p>When you write code like this:</p><pre>Animal* ptr = new Dog();<br>delete ptr;</pre><p>There is a potential problem. The destructor of Dog might not run correctly.</p><p>The fix (for now, just memorize the pattern):</p><pre>class Animal {<br>public:<br>    virtual ~Animal() {}  // ← Add this to the parent class<br>};</pre><p>We will explain what virtual means and why this works in Shot #4 (Polymorphism). For now, just remember: if you use parent pointers to child objects, make the parent destructor virtual.</p><h3>Quick Summary</h3><ul><li>A parent pointer can point to a child object — Because child IS-A parent.</li><li>You can only call parent methods through that pointer — The compiler only sees the parent type.</li></ul><h3>What’s Next?</h3><p>You are now ready for Shot #4 — Polymorphism.</p><p>There, you will learn how to make a parent pointer call the child’s version of a method automatically. That is the real magic of OOP.</p><p><em>Found this helpful? Clap 👏 and follow for more C++ Shots!</em></p><p>Previous: [C++ Shots 3 — Inheritance]<br>Next: C++ Shots 4 — Polymorphism (coming soon)</p><h3>End</h3><p>Questions? I am here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149bd53e2526" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Shots 3 — OOP: What Is Inheritance? (And Why It’s Like a Family Tree)]]></title>
            <link>https://medium.com/@kodarpiece/c-shots-3-oop-what-is-inheritance-and-why-its-like-a-family-tree-6c056d0e0027?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c056d0e0027</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 10:54:41 GMT</pubDate>
            <atom:updated>2026-06-21T10:54:41.697Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous shots, you learned:</p><ul><li><strong>Shot #1</strong> — What a class and an object are.</li><li><strong>Shot #2</strong> — How to hide data using encapsulation (private, public, protected).</li></ul><p>Now it’s time for the third shot of OOP: inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hXZI563LJ7bv8MW1nefgQ.png" /></figure><p>Think of a family tree. A child inherits traits from their parents — eye color, height, maybe a talent for music. But the child also has their own unique features.</p><p>In C++, inheritance works the same way;</p><h3>Inheritance in C++ — The Simple Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzFzC1BsiwRv0OBgs9znCQ.png" /></figure><p>Inheritance is when one class gets all the properties and behaviors from another class.</p><h4>The One-Sentence Summary</h4><blockquote>A child class automatically receives everything from its parent class.</blockquote><h4>The Pizza Analogy 🍕</h4><p>Think of a base pizza (dough + sauce + cheese).</p><ul><li><strong>Margherita</strong> inherits from base pizza → just adds basil</li><li><strong>Pepperoni</strong> inherits from base pizza → just adds pepperoni</li></ul><p>You don’t remake the dough every time. You inherit it.</p><h4>How to code it?</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>// ==============================================<br>// BASE CLASS (also called PARENT CLASS)<br>// ==============================================<br>// This is the &quot;Pizza&quot; class.<br>// It contains the basic features that ALL pizzas share.<br>class Pizza {<br>public:<br>    // Public method - can be called from anywhere<br>    void hasDough() { <br>        cout &lt;&lt; &quot;Has dough&quot; &lt;&lt; endl; <br>    }<br>    <br>    // Public method - can be called from anywhere<br>    void hasCheese() { <br>        cout &lt;&lt; &quot;Has cheese&quot; &lt;&lt; endl; <br>    }<br>};<br><br>// ==============================================<br>// DERIVED CLASS (also called CHILD CLASS)<br>// ==============================================<br>// The colon &#39;:&#39; means &quot;inherits from&quot;<br>// &#39;public Pizza&#39; means we keep all access levels the same<br>// Pepperoni IS-A type of Pizza<br>class Pepperoni : public Pizza {  <br>public:<br>    // This is a NEW method that ONLY Pepperoni has<br>    // Regular pizza doesn&#39;t have pepperoni!<br>    void hasPepperoni() { <br>        cout &lt;&lt; &quot;Has pepperoni&quot; &lt;&lt; endl; <br>    }<br>};<br><br>// ==============================================<br>// MAIN FUNCTION - Where the program runs<br>// ==============================================<br>int main() {<br>    <br>    // Create an object (instance) of the Pepperoni class<br>    // This creates one specific pepperoni pizza<br>    Pepperoni p;<br>    <br>    // ✅ Call a method from the PARENT class (Pizza)<br>    // Even though we never wrote &#39;hasDough()&#39; inside Pepperoni,<br>    // Pepperoni INHERITED it from Pizza.<br>    // This works because: Pepperoni IS-A Pizza<br>    p.hasDough();     // Output: Has dough<br>    <br>    // ✅ Call another method from the PARENT class (Pizza)<br>    // Also inherited automatically<br>    p.hasCheese();    // Output: Has cheese<br>    <br>    // ✅ Call a method from the CHILD class (Pepperoni)<br>    // This method belongs ONLY to Pepperoni, not to regular Pizza<br>    p.hasPepperoni(); // Output: Has pepperoni<br>    <br>    return 0;  // Program finished successfully<br>}</pre><h3>Why Do We Need Inheritance?</h3><p>Without inheritance, you would copy and paste the same code over and over.</p><p>Imagine you’re building a game with three character types: Warrior, Mage, and Archer. They all share common things:</p><ul><li>Health.</li><li>Power.</li><li>Position (x, y).</li><li>walk() method.</li><li>takeDamage() method.</li></ul><p>Without inheritance, you’d write the same code three times. With inheritance, you write it once in a base class, and the others reuse it.</p><p>Inheritance gives you two superpowers:</p><ol><li><strong>Code Reuse</strong> — Write once, use many times.</li><li><strong>Hierarchy</strong> — Organize related classes logically.</li></ol><h3>The Vocabulary of Inheritance</h3><ul><li><strong>Base class (parent): </strong>The class being inherited from.</li><li><strong>Derived class (child): </strong>The class that inherits.</li><li><strong>public inheritance: </strong>The most common type. “Dog <em>is-a</em> Animal”.</li><li><strong>Override:</strong> Replace a parent’s method with a new version.<br>(<em>We will cover overriding in another shot. For now, just remember the word)</em>.</li></ul><h3>Another Simple Example — Animals</h3><p>Let’s start with a base class Animal:</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br><br>class Animal {<br>protected:  // Remember from Shot #2? Child classes can access this!<br>    string name;<br>    int age;<br><br>public:<br>    Animal(string n, int a) : name(n), age(a) {}<br><br>    void eat() {<br>        cout &lt;&lt; name &lt;&lt; &quot; is eating.&quot; &lt;&lt; endl;<br>    }<br><br>    void sleep() {<br>        cout &lt;&lt; name &lt;&lt; &quot; is sleeping.&quot; &lt;&lt; endl;<br>    }<br><br>    void introduce() {<br>        cout &lt;&lt; &quot;I am &quot; &lt;&lt; name &lt;&lt; &quot;, age &quot; &lt;&lt; age &lt;&lt; &quot;.&quot; &lt;&lt; endl;<br>    }<br>};</pre><p>Now, let’s create a derived class Dog:</p><pre>class Dog : public Animal {  // &quot;public Animal&quot; means public inheritance<br>public:<br>    // Constructor must call the base class constructor<br>    Dog(string n, int a) : Animal(n, a) {}<br><br>    // New method that only Dog has<br>    void bark() {<br>        cout &lt;&lt; name &lt;&lt; &quot; says: Woof! Woof!&quot; &lt;&lt; endl;<br>    }<br><br>    // Override: Dog has its own version of introduce()<br>    void introduce() {<br>        cout &lt;&lt; &quot;I am a dog named &quot; &lt;&lt; name &lt;&lt; &quot;, age &quot; &lt;&lt; age &lt;&lt; &quot;. Woof!&quot; &lt;&lt; endl;<br>    }<br>};</pre><p>And a derived class Cat:</p><pre>class Cat : public Animal {<br>public:<br>    Cat(string n, int a) : Animal(n, a) {}<br><br>    void meow() {<br>        cout &lt;&lt; name &lt;&lt; &quot; says: Meow~&quot; &lt;&lt; endl;<br>    }<br><br>    void introduce() override {  // &#39;override&#39; is optional but good practice<br>        cout &lt;&lt; &quot;I am a cat named &quot; &lt;&lt; name &lt;&lt; &quot;. Meow~&quot; &lt;&lt; endl;<br>    }<br>};</pre><p>Now let’s use them:</p><pre>int main() {<br>    Animal generic(&quot;Generic creature&quot;, 5);<br>    Dog rex(&quot;Rex&quot;, 3);<br>    Cat whiskers(&quot;Whiskers&quot;, 2);<br><br>    cout &lt;&lt; &quot;--- Animal ---&quot; &lt;&lt; endl;<br>    generic.introduce();<br>    generic.eat();<br><br>    cout &lt;&lt; &quot;\n--- Dog ---&quot; &lt;&lt; endl;<br>    rex.introduce();   // Dog&#39;s version (overridden)<br>    rex.eat();         // Inherited from Animal<br>    rex.bark();        // Only Dog has this<br><br>    cout &lt;&lt; &quot;\n--- Cat ---&quot; &lt;&lt; endl;<br>    whiskers.introduce();  // Cat&#39;s version<br>    whiskers.sleep();      // Inherited from Animal<br>    whiskers.meow();       // Only Cat has this<br><br>    return 0;<br>}</pre><p>output:</p><pre>--- Animal ---<br>I am Generic creature, age 5.<br>Generic creature is eating.<br><br>--- Dog ---<br>I am a dog named Rex, age 3. Woof!<br>Rex is eating.<br>Rex says: Woof! Woof!<br><br>--- Cat ---<br>I am a cat named Whiskers. Meow~<br>Whiskers is sleeping.<br>Whiskers says: Meow~</pre><p>Notice: rex.eat() works even though we never wrote eat() inside Dog. That&#39;s inheritance in action.</p><h3>The Three Types of Inheritance</h3><p>C++ supports three inheritance modes. For beginners, focus on public:<br>(<em>These are pretty advanced, but good to keep in mind.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySMzv8YZq8rQ16sDzgHH4w.png" /></figure><ul><li>class Dog : public Animal Most common. &quot;Dog is an Animal&quot;.</li><li>class Dog : protected Animal Rare. Used in advanced scenarios.</li><li>class Dog : private Animal Rare. &quot;Dog has an Animal&quot; (composition).</li></ul><blockquote>Use public inheritance unless you have a specific reason not to.</blockquote><h3>What Gets Inherited?</h3><p>Let’s break down exactly what a child class gets from its parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg6QNQvID0QqfRJan5ntCQ.png" /></figure><h4>1. Public Members → Yes, inherited as public</h4><p>Public methods and data from the parent become public members of the child.</p><pre>class Animal {<br>public:<br>    void eat() { cout &lt;&lt; &quot;Eating&quot; &lt;&lt; endl; }  // Public method<br>};<br><br>class Dog : public Animal {  // Dog inherits from Animal<br>    // Dog automatically has eat() even though we didn&#39;t write it<br>};<br><br>int main() {<br>    Dog d;<br>    d.eat();  // ✅ Works! eat() is inherited from Animal<br>    return 0;<br>}</pre><h4>2. Protected Members → Yes, inherited as protected</h4><p>Protected members are inherited, but they stay protected — only the child class can access them, not outsiders.</p><pre>class Animal {<br>protected:<br>    int age;  // Protected member<br>};<br><br>class Dog : public Animal {<br>public:<br>    void setAge(int a) {<br>        age = a;  // ✅ Works! Child can access protected member from parent<br>    }<br>};<br><br>int main() {<br>    Dog d;<br>    // d.age = 5;  // ❌ ERROR! Outsider (main function) cannot access protected member<br>    d.setAge(5);   // ✅ Works because setAge is public<br>    return 0;<br>}</pre><h4>3. Private Members → The child OWNS them but CANNOT access them directly</h4><p>This is a very important point. When a child inherits from a parent, the private members of the parent are still inside the child object — they take up memory and exist. However, the child class cannot access them directly by name. Only the parent’s own methods can touch them.</p><p>Think of it like a house with a locked room. The child inherits the house (including the locked room), but does not have the key. The room exists, but the child cannot enter it.</p><pre>class Animal {<br>private:<br>    int secretCode = 42;  // Private member<br>public:<br>    int getSecretCode() { return secretCode; }  // Public getter (the &quot;key&quot;)<br>};<br><br>class Dog : public Animal {<br>    // Dog OWNS secretCode (it exists inside every Dog object)<br>    // But Dog CANNOT write: cout &lt;&lt; secretCode; (direct access is forbidden)<br>public:<br>    void showSecret() {<br>        // cout &lt;&lt; secretCode;  // ❌ ERROR! Cannot access private member directly<br>        cout &lt;&lt; getSecretCode();  // ✅ Works! Access through parent&#39;s public method<br>    }<br>};<br><br>int main() {<br>    Dog d;<br>    // d.secretCode = 99;  // ❌ ERROR! Cannot access private member from outside<br>    d.showSecret();        // ✅ Works – shows 42<br>    return 0;<br>}</pre><p><strong>Key takeaway:</strong> The child class owns the private data (it exists inside the child object), but cannot access it directly — it must go through the parent’s public or protected methods.</p><h4>4. Constructors → Not inherited, but child must call them</h4><p>Constructors are not inherited. However, the child constructor must explicitly call the parent constructor.</p><pre>class Animal {<br>public:<br>    Animal(string n) {  // Parent constructor with parameter<br>        cout &lt;&lt; &quot;Animal created: &quot; &lt;&lt; n &lt;&lt; endl;<br>    }<br>};<br><br>class Dog : public Animal {<br>public:<br>    // Dog(string n) : Animal(n) is REQUIRED<br>    Dog(string n) : Animal(n) {  // ✅ Must call parent constructor<br>        cout &lt;&lt; &quot;Dog created&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Dog d(&quot;Rex&quot;);  // First calls Animal(&quot;Rex&quot;), then Dog constructor<br>    return 0;<br>}</pre><p><strong>Output:</strong></p><pre>Animal created: Rex<br>Dog created</pre><p><strong>What happens if you forget to call the parent constructor?</strong></p><p>The compiler tries to call a default constructor (with no parameters). If the parent doesn’t have one, you get a compilation error.</p><h4>5. Destructors → Not inherited, but called automatically</h4><p>Destructors are not inherited, but when a child object is destroyed, the parent destructor runs automatically in reverse order (child first, then parent).</p><pre>class Animal {<br>public:<br>    ~Animal() { cout &lt;&lt; &quot;Animal destroyed&quot; &lt;&lt; endl; }  // Parent destructor<br>};<br><br>class Dog : public Animal {<br>public:<br>    ~Dog() { cout &lt;&lt; &quot;Dog destroyed&quot; &lt;&lt; endl; }  // Child destructor<br>};<br><br>int main() {<br>    Dog d;<br>    // When main ends, d is destroyed:<br>    // First: Dog destructor runs<br>    // Then: Animal destructor runs automatically<br>    return 0;<br>}</pre><p><strong>Output:</strong></p><pre>Dog destroyed<br>Animal destroyed</pre><p>You do not need to write anything special. C++ handles this automatically.</p><h3>The Inheritance Chain</h3><p>If X inherits from Y, and Y inherits from Z, then X automatically inherits from Z as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBswc0X48rU1XDpmu2Iueg.png" /></figure><p>This is called transitive inheritance (or an inheritance hierarchy).</p><pre>Z (grandparent)<br>↑<br>Y (parent)<br>↑<br>X (child)</pre><h4>Simple Example</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Z {  // Grandparent<br>protected:<br>    string grandparentDNA = &quot;DNA from Z&quot;;<br>public:<br>    void zFeature() {<br>        cout &lt;&lt; &quot;Feature from Z&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Y : public Z {  // Parent inherits from Z<br>protected:<br>    string parentDNA = &quot;DNA from Y&quot;;<br>public:<br>    void yFeature() {<br>        cout &lt;&lt; &quot;Feature from Y&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class X : public Y {  // Child inherits from Y<br>public:<br>    void showAll() {<br>        cout &lt;&lt; grandparentDNA &lt;&lt; endl;  // ✅ From Z<br>        cout &lt;&lt; parentDNA &lt;&lt; endl;       // ✅ From Y<br>        zFeature();                       // ✅ From Z<br>        yFeature();                       // ✅ From Y<br>        cout &lt;&lt; &quot;Feature from X&quot; &lt;&lt; endl; // ✅ Own feature<br>    }<br>};<br><br>int main() {<br>    X obj;<br>    obj.showAll();<br>    return 0;<br>}</pre><p><strong>Output:</strong></p><pre>DNA from Z<br>DNA from Y<br>Feature from Z<br>Feature from Y<br>Feature from X</pre><p>See? X can access members from both Y AND Z.</p><h4>Visual Representation</h4><pre>        Z<br>        | (has feature1)<br>        Y<br>        | (has feature1 + feature2)<br>        X<br>        (has feature1 + feature2 + feature3)</pre><p>Every level adds new features but keeps all the features from above.</p><h4>Important Rule: Constructor Chain</h4><p>When you create an object of X, constructors are called from top to bottom:</p><ol><li>Z constructor runs first</li><li>Y constructor runs second</li><li>X constructor runs last</li></ol><pre>class Z {<br>public:<br>    Z() { cout &lt;&lt; &quot;Z constructed&quot; &lt;&lt; endl; }<br>};<br><br>class Y : public Z {<br>public:<br>    Y() { cout &lt;&lt; &quot;Y constructed&quot; &lt;&lt; endl; }<br>};<br><br>class X : public Y {<br>public:<br>    X() { cout &lt;&lt; &quot;X constructed&quot; &lt;&lt; endl; }<br>};<br><br>int main() {<br>    X obj;<br>    // Output:<br>    // Z constructed<br>    // Y constructed<br>    // X constructed<br>}</pre><p>Destructors run in reverse order: X → Y → Z.</p><h3>Let’s quickly recap what you discovered in this shot:</h3><ul><li>A child class receives everything from its parent class.</li><li>Public members stay public. Protected members are accessible to children but hidden from outsiders. Private members exist inside the child but cannot be accessed directly.</li><li>The child owns the private data but needs the parent’s getters and setters to touch it.</li><li>Constructors are not inherited — you must call the parent constructor explicitly.</li><li>Destructors are not inherited but run automatically in reverse order.</li><li>Inheritance can chain: if X inherits from Y, and Y inherits from Z, then X inherits from Z as well.</li></ul><h3>That’s All for This Shot.</h3><h3>Congratulations 🎉.</h3><p>You Are Building Real C++ Skills.</p><h3>End</h3><p>Questions? I am here.</p><p>— Kodar Piece.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c056d0e0027" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Shots 2 — OOP: What Is Encapsulation? (And Why It’s Like a Capsule Pill)]]></title>
            <link>https://medium.com/@kodarpiece/c-shots-2-oop-what-is-encapsulation-and-why-its-like-a-capsule-pill-69398500ae9d?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/69398500ae9d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 14:02:57 GMT</pubDate>
            <atom:updated>2026-06-17T14:02:57.034Z</atom:updated>
            <content:encoded><![CDATA[<p>When you first hear the word <strong>encapsulation</strong> in C++, think of a medicine capsule.</p><p>The capsule holds the drug inside (hidden from direct touch), but it still provides a clear way to take it — by swallowing the capsule itself.</p><p>In C++ Object-Oriented Programming (OOP), encapsulation works the same way: <strong>bundle data and methods together, and hide the internal details from the outside world.</strong></p><h3>Why Do We Need Encapsulation?</h3><p>Without encapsulation, your program’s data becomes public — anyone can change it accidentally, break it, or put it in an invalid state.</p><p>Encapsulation gives you two superpowers:</p><ul><li><strong>Control</strong>— You decide who can read or write the data.</li><li><strong>Safety</strong> — Outsiders can’t mess up the internal logic.</li></ul><h4>Encapsulation and Abstraction</h4><p>Another important concept is <strong>abstraction</strong>. Abstraction simply means hiding the complexity of details. When you write code, you don’t think about the assembly code or how your code is compiled. When you write in a compiled language like C++, you don’t think about logic gates. And when you work with logic gates, you don’t think about individual transistors. All of this is possible because good programmers create layers of abstraction so that the next person who comes along finds it easier to understand and build upon.</p><p>The same applies to your own code. When your program becomes large and complex, you don’t want to think about how to protect or insert data every single time. Instead, you simply use the functions you’ve already built — they handle the safety and complexity for you, without fear of breaking anything.</p><p>Encapsulation is one of the main tools that enables this kind of abstraction. By hiding the internal data and exposing only a clean public interface, you create a simplified view of your class.</p><h3>The Three Levels of Encapsulation</h3><p>There are three levels of protection you can apply to your class members.</p><h4>1. private:</h4><p><strong>Only the class itself can see or use it.</strong></p><p>When you create a private member, you cannot use it directly outside the class scope. To create a private member, add the <em>private:</em> keyword at the top of it:</p><pre>class class_name {<br>private:<br>  // add private member 1<br>  // add private member 2<br>  // …<br>  // add private member n<br>};</pre><p><strong>Important:</strong> <strong>private</strong> is the default access mode. If you do not specify any mode, the members will be private.</p><pre>class class_name {<br>  // add private member 1 (default)<br>  // add private member 2 (default)<br>};</pre><p><strong>For clarity</strong>, always specify the mode explicitly.</p><p><strong>Example:</strong></p><pre>class Student {<br>private:<br>  std::string fullName;<br>  double degree;<br>// fullName and degree are accessible here (inside the class)<br> // This is allowed: degree = 95.5;<br>};<br>// Outside the class:<br>// fullName is NOT accessible here<br>// studentObject.degree → ERROR! Private member.</pre><h4>2. public:</h4><p><strong>Anyone can see or use it.</strong></p><p>This means you can access it directly from any place in your code. To create a public member, add the <em>public:</em> keyword at the top of it:</p><pre>class class_name {<br>public:<br>  // add public member 1<br>  // add public member 2<br>  // …<br>  // add public member n<br>};</pre><p>This mode is used specifically for <strong>member functions</strong> (methods). You can add member data as public, but <strong>it’s bad practice</strong> — it breaks encapsulation.</p><p><strong>Example:</strong></p><pre>class Student {<br>private:<br>  std::string fullName;<br>  double degree;<br><br>public:<br>  std::string get_full_name() {<br>    return fullName; // Allowed because we are inside the class scope<br>  }<br><br>  void set_degree(double d) {<br>    if (d &gt;= 0 &amp;&amp; d &lt;= 100)<br>    degree = d; // Validation inside the class<br>  }<br>};<br><br>// Using the class:<br>Student s;<br>std::cout &lt;&lt; s.get_full_name() &lt;&lt; &quot;\n&quot;; // Allowed because get_full_name() is public<br>// s.fullName; → ERROR! Private member, cannot access directly</pre><h4>3. protected:</h4><p>Only the class itself and its derived classes (children) can see or use it.</p><p>If you don’t know what derived classes are yet, think of it this way:</p><ul><li><strong>private</strong> = only <strong>this class</strong>.</li><li><strong>protected</strong> = this class + <strong>any class that inherits from it.</strong></li></ul><p>For a beginner, just remember: <strong>protected</strong> is like <strong>private</strong>, but it allows <strong>future child classes</strong> to access the member. If you are not using inheritance, <strong>protected</strong> behaves exactly like <strong>private</strong>.</p><p>To create a protected member, add the <em>protected:</em> keyword:</p><pre>class class_name {<br>protected:<br>  // add protected member 1<br>  // add protected member 2<br>  // …<br>  // add protected member n<br>};</pre><p><strong>Example (simplified for beginners):</strong></p><pre>class Animal {<br>private:<br>  int secretCode; // Only Animal class can access this<br><br>protected:<br>  int age; // Animal and any derived class (e.g., Dog) can access this<br><br>public:<br>  std::string name; // Anyone can access this<br>};<br><br>// If you later create a Dog class that inherits from Animal:<br>// Dog can access &#39;age&#39; (protected) but NOT &#39;secretCode&#39; (private)</pre><blockquote><strong>Beginner tip:</strong> Until you learn inheritance, just use <strong>private</strong> for data and <strong>public </strong>for methods. <strong>protected</strong> will make more sense later.</blockquote><h3>Full Example</h3><p>Here is a complete, easy-to-understand example of encapsulation in action:</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>using namespace std;<br><br>// Class representing a Bank Account<br>class BankAccount {<br>private:<br>    // PRIVATE DATA: hidden from outside<br>    string accountHolder;<br>    double balance;<br>    string accountNumber;<br><br>    // Private method: helper function (cannot be called from outside)<br>    void logTransaction(string type, double amount) {<br>        cout &lt;&lt; &quot;[LOG] &quot; &lt;&lt; type &lt;&lt; &quot;: &quot; &lt;&lt; amount &lt;&lt; &quot; | Balance: &quot; &lt;&lt; balance &lt;&lt; endl;<br>    }<br><br>public:<br>    // PUBLIC CONSTRUCTOR: runs when object is created<br>    BankAccount(string holder, string accNum, double initialBalance) {<br>        accountHolder = holder;<br>        accountNumber = accNum;<br><br>        // Validation: no negative balance<br>        if (initialBalance &gt;= 0) {<br>            balance = initialBalance;<br>            logTransaction(&quot;Initial deposit&quot;, initialBalance);<br>        } else {<br>            balance = 0;<br>            logTransaction(&quot;Initial deposit (adjusted from negative)&quot;, 0);<br>        }<br>    }<br><br>    // PUBLIC METHOD: get balance (read-only access)<br>    double getBalance() const {<br>        return balance;  // Outside world can SEE but not CHANGE directly<br>    }<br><br>    // PUBLIC METHOD: get account holder name<br>    string getAccountHolder() const {<br>        return accountHolder;<br>    }<br><br>    // PUBLIC METHOD: deposit money (with validation)<br>    void deposit(double amount) {<br>        if (amount &gt; 0) {<br>            balance += amount;<br>            logTransaction(&quot;Deposit&quot;, amount);<br>            cout &lt;&lt; &quot;Successfully deposited: $&quot; &lt;&lt; amount &lt;&lt; endl;<br>        } else {<br>            cout &lt;&lt; &quot;Error: Deposit amount must be positive!&quot; &lt;&lt; endl;<br>        }<br>    }<br><br>    // PUBLIC METHOD: withdraw money (with validation)<br>    void withdraw(double amount) {<br>        if (amount &lt;= 0) {<br>            cout &lt;&lt; &quot;Error: Withdraw amount must be positive!&quot; &lt;&lt; endl;<br>        } else if (amount &gt; balance) {<br>            cout &lt;&lt; &quot;Error: Insufficient funds! Available: $&quot; &lt;&lt; balance &lt;&lt; endl;<br>        } else {<br>            balance -= amount;<br>            logTransaction(&quot;Withdraw&quot;, amount);<br>            cout &lt;&lt; &quot;Successfully withdrew: $&quot; &lt;&lt; amount &lt;&lt; endl;<br>        }<br>    }<br><br>    // PUBLIC METHOD: transfer money to another account<br>    void transfer(BankAccount&amp; target, double amount) {<br>        if (amount &lt;= 0) {<br>            cout &lt;&lt; &quot;Error: Transfer amount must be positive!&quot; &lt;&lt; endl;<br>        } else if (amount &gt; balance) {<br>            cout &lt;&lt; &quot;Error: Cannot transfer. Insufficient funds!&quot; &lt;&lt; endl;<br>        } else {<br>            withdraw(amount);      // Take money from this account<br>            target.deposit(amount); // Give money to target account<br>            cout &lt;&lt; &quot;Transferred $&quot; &lt;&lt; amount &lt;&lt; &quot; to &quot; &lt;&lt; target.getAccountHolder() &lt;&lt; endl;<br>        }<br>    }<br>};<br><br>// Main function to demonstrate encapsulation<br>int main() {<br>    // Create two bank accounts<br>    BankAccount alice(&quot;Alice Smith&quot;, &quot;ACC001&quot;, 1000.00);<br>    BankAccount bob(&quot;Bob Johnson&quot;, &quot;ACC002&quot;, 500.00);<br><br>    cout &lt;&lt; &quot;\n--- Initial Balances ---&quot; &lt;&lt; endl;<br>    cout &lt;&lt; alice.getAccountHolder() &lt;&lt; &quot;: $&quot; &lt;&lt; alice.getBalance() &lt;&lt; endl;<br>    cout &lt;&lt; bob.getAccountHolder() &lt;&lt; &quot;: $&quot; &lt;&lt; bob.getBalance() &lt;&lt; endl;<br><br>    cout &lt;&lt; &quot;\n--- Transactions ---&quot; &lt;&lt; endl;<br>    alice.deposit(200);           // Alice deposits $200<br>    alice.withdraw(50);           // Alice withdraws $50<br>    alice.transfer(bob, 300);     // Alice transfers $300 to Bob<br><br>    cout &lt;&lt; &quot;\n--- Final Balances ---&quot; &lt;&lt; endl;<br>    cout &lt;&lt; alice.getAccountHolder() &lt;&lt; &quot;: $&quot; &lt;&lt; alice.getBalance() &lt;&lt; endl;<br>    cout &lt;&lt; bob.getAccountHolder() &lt;&lt; &quot;: $&quot; &lt;&lt; bob.getBalance() &lt;&lt; endl;<br><br>    // THE FOLLOWING WOULD CAUSE ERRORS (encapsulation in action):<br>    // alice.balance = 9999;       // ERROR: balance is private!<br>    // cout &lt;&lt; alice.balance;       // ERROR: cannot access private member!<br>    // alice.logTransaction(...);   // ERROR: logTransaction is private!<br><br>    return 0;<br>}</pre><p>Expected Output:</p><pre>[LOG] Initial deposit: 1000 | Balance: 1000<br>[LOG] Initial deposit: 500 | Balance: 500<br><br>--- Initial Balances ---<br>Alice Smith: $1000<br>Bob Johnson: $500<br><br>--- Transactions ---<br>[LOG] Deposit: 200 | Balance: 1200<br>Successfully deposited: $200<br>[LOG] Withdraw: 50 | Balance: 1150<br>Successfully withdrew: $50<br>[LOG] Withdraw: 300 | Balance: 850<br>Successfully withdrew: $300<br>[LOG] Deposit: 300 | Balance: 800<br>Successfully deposited: $300<br>Transferred $300 to Bob Johnson<br><br>--- Final Balances ---<br>Alice Smith: $850<br>Bob Johnson: $800</pre><h3>Takeaway</h3><ul><li><strong>Encapsulation: </strong>Bundling data and methods together, hiding internal details.</li><li><strong>Private: </strong>Accessible only inside the class. Use this for data.</li><li><strong>Public: </strong>Accessible from anywhere. Use this for methods (interface).</li><li><strong>Protected: </strong>Accessible inside the class + child classes. (Learn this later.)</li><li><strong>Why? </strong>Control + Safety. Prevents accidental or invalid changes.</li></ul><h4>Remember these three rules:</h4><ol><li>Make your data <strong>private</strong> — never expose raw data directly.</li><li>Provide <strong>public</strong> methods — these are the “buttons” others can press.</li><li>Validate inside setters — never trust outside input.</li></ol><p>Encapsulation is not just a rule — it’s a habit that will save you hours of debugging. When your program crashes, you’ll know exactly where to look: inside your class methods, not scattered across 1000 lines of code.</p><h3>End</h3><p>Found this helpful? Clap 👏 and follow for more C++ Shots!</p><p>Questions? I am still here.</p><p>— Kodar Piece.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69398500ae9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Shots: 1 — OOP Basics Terms]]></title>
            <link>https://medium.com/@kodarpiece/c-shots-1-oop-basics-terms-4bc99cf10780?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc99cf10780</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 17:03:41 GMT</pubDate>
            <atom:updated>2026-06-12T17:03:41.137Z</atom:updated>
            <content:encoded><![CDATA[<p>In this first C++ Shot, we’ll learn the essential terms you need before writing any OOP code: data, actions, objects, paradigms, and classes.</p><h3>What is Data?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pl1zbWBRdSTty9O34LZxkQ.png" /></figure><p>Data is the information your program stores, remembers, or works with.</p><p>In code, data lives in variables and data structures (numbers, strings, arrays, objects, etc.).</p><p>Examples:</p><ul><li>A user’s age: 25</li><li>A product price: $19.99</li><li>A list of names: [&quot;Anna&quot;, &quot;Bob&quot;]</li></ul><h3>What is an Action?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Uk8Boocoo5TwsVK0OoiZg.png" /></figure><p>An action is the behavior or work your program performs on or with data.</p><p>In code, actions are functions, procedures, methods, or operations.</p><p>Examples:</p><ul><li>Calculate the total price after tax.</li><li>Save a user’s name to a database.</li><li>Print a receipt.</li></ul><h3>What is an Object?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LajO7USqhTE2vQJA5rOc0Q.png" /></figure><p>An object is a single bundle that holds both data and actions together — as one unit.</p><p>The members of an object are divided into two types:</p><ul><li>The data inside an object is called its attributes (or properties/fields).</li><li>The actions inside an object are called its methods.</li></ul><h4>Analogy</h4><p>Think of a car. A car has data (attributes) like color, model, height, etc. It also has actions like moving, stopping, and increasing speed. In OOP, we can model the car as an object with its own properties and methods.</p><h3>What is a Programming Paradigm?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ve7Ur1EXU6pwykQfRqAuPg.png" /></figure><p>A programming paradigm is a fundamental way of thinking about how code should be structured and how it should solve problems.</p><p>Think of it like a philosophy or approach that you choose to structure your code.</p><p>Choosing a paradigm is the first step — you decide how to plan your program before writing it.</p><h3>The Main Paradigms</h3><h4>1. Procedural</h4><p>Create step‑by‑step logic by giving the computer a list of instructions to execute one after another.</p><p>Data and actions are separate entities, and the programmer must combine them to get the desired result.</p><p><strong>Example (simulate car moving):</strong></p><pre>// Procedural style<br>int carID = 1234;<br>int carKmMoving = 0;<br>carKmMoving = carKmMoving + 1;   // move 1 km<br>printf(&quot;Car %d moved %d km.\n&quot;, carID, carKmMoving);</pre><h4>2. Functional</h4><p>Treat computation as evaluating mathematical functions without changing (mutating) data.</p><p>Functions take inputs and return outputs, leaving original data unchanged.</p><p><strong>Example (simulate car moving):</strong></p><pre>// Functional style (pseudo-C)<br>int move_car(int currentKm) {<br>    return currentKm + 1;   // returns new value, doesn&#39;t modify original<br>}<br><br>int carID = 1234;<br>int carKmMoving = 0;<br>carKmMoving = move_car(carKmMoving);<br>printf(&quot;Car %d moved %d km.\n&quot;, carID, carKmMoving);</pre><h4>3. Object-Oriented (OOP)</h4><p>Bundle data and actions together into objects that interact.</p><p>The focus is on creating user‑defined data types that contain both properties and methods.</p><p><strong>Example (simulate car moving):</strong></p><pre>// Simple Object-Oriented example in C++<br>#include &lt;iostream&gt;<br>using namespace std;<br><br>// Define a Car type that bundles data and actions together<br>class Car {<br>public:<br>    int km;           // data (attribute)<br><br>    void move() {     // action (method)<br>        km = km + 1;<br>    }<br>};<br><br>int main() {<br>    Car myCar;        // create a Car object<br>    myCar.km = 0;     // set initial data<br><br>    myCar.move();     // perform an action<br>    myCar.move();     // another action<br><br>    cout &lt;&lt; &quot;Car has moved &quot; &lt;&lt; myCar.km &lt;&lt; &quot; km.\n&quot;;<br>    return 0;<br>}</pre><h3>What is a Class?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5N6o3026ZSM87FiyNE8Yg.png" /></figure><p>A class is a blueprint or template for creating objects.</p><h4>Analogy</h4><p>Class — A house blueprint plans showing how a house should be built</p><p>Object — An actual house built from that blueprint</p><ul><li>You can build many houses from one blueprint.</li><li>The blueprint itself is not a house you can live in.</li><li>The blueprint defines what every house will have (rooms, doors, windows).</li></ul><h4>In Code</h4><p>A class defines:</p><ul><li>What data (attributes) every object will have</li><li>What actions (methods) every object can perform</li></ul><p>An object is a specific instance of that class, with real values filled in.</p><h3>Think of a Class as a Data Type</h3><p>Here is an important way to understand classes and objects:</p><p>A class is like creating your own data type. An object is a variable of that data type.</p><p>You already know the int data type. int is not a variable — it is a description of what kind of data a variable can hold.</p><p>When you write int x = 5;, you are saying:</p><ul><li>int = the type (describes characteristics: whole numbers, can be negative or positive, uses 4 bytes of memory)</li><li>x = the variable (actual storage in memory holding a specific value).</li><li>5 = the value.</li></ul><p>A class is just a custom data type you design yourself. Once you create the Dog class, you can use it anywhere like you use int, string, or double.</p><h4>Example:</h4><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>using namespace std;<br><br>// &#39;class&#39; keyword: we are creating a blueprint for objects<br>// &#39;Dog&#39; is the name of the class (starts with capital letter by convention)<br>class Dog {<br><br>// &#39;public:&#39; means everything below is accessible from outside the class<br>// (other parts of the program can see and use these)<br>public:<br>    <br>    // ----- DATA (attributes / properties) -----<br>    <br>    // &#39;name&#39; is the name of this attribute<br>    // This line says: every Dog object will have a &#39;name&#39;<br>    string name;    // data: stores the dog&#39;s name (ex: &quot;Buddy&quot;)<br>    <br>    // &#39;age&#39; is the name of this attribute<br>    // This line says: every Dog object will have an &#39;age&#39;<br>    int age;        // data: stores the dog&#39;s age (ex: 3)<br>    <br>    // ----- ACTIONS (methods) -----<br>    <br>    // &#39;bark&#39; is the name of the method<br>    void bark() {   // action: what the dog can DO<br><br>        // The line below prints: &quot;[name] says: Woof!&quot;<br>        cout &lt;&lt; name &lt;&lt; &quot; says: Woof!&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    <br>    // ----- CREATING AN OBJECT (INSTANCE) -----<br>    <br>    // &#39;Dog&#39; is the class name (the blueprint)<br>    // &#39;myDog&#39; is the name of the object we are creating<br>    // This line says: &quot;build a new Dog object and call it myDog&quot;<br>    Dog myDog;              // create object from the Dog class<br>    <br>    // ----- SETTING DATA (attributes) -----<br>    <br>    // &#39;.&#39; (dot operator) accesses a member of the object<br>    // &#39;myDog.name&#39; means &quot;go inside myDog and find the &#39;name&#39; attribute&quot;<br>    // &#39;=&#39; assigns a value to that attribute<br>    myDog.name = &quot;Buddy&quot;;   // set the dog&#39;s name to &quot;Buddy&quot;<br>    <br>    // &#39;myDog.age&#39; accesses the age attribute<br>    myDog.age = 3;          // set the dog&#39;s age to 3<br>    <br>    // ----- CALLING AN ACTION (method) -----<br>    <br>    // &#39;myDog.bark()&#39; means &quot;go inside myDog and execute the bark() method&quot;<br>    // The bark() method uses &#39;name&#39; (which is &quot;Buddy&quot;) to print the message<br>    myDog.bark();           // call the dog&#39;s bark action<br>    <br>    // ----- PROGRAM END -----<br>    <br>    return 0;<br>    <br>}<br><br>// =============================================<br>// WHAT HAPPENS WHEN YOU RUN THIS PROGRAM:<br>// =============================================<br><br>// 1. Computer reads the class Dog (blueprint)<br>// 2. Computer enters main() function<br>// 3. Computer creates a Dog object named &#39;myDog&#39;<br>// 4. Computer sets myDog.name = &quot;Buddy&quot;<br>// 5. Computer sets myDog.age = 3<br>// 6. Computer calls myDog.bark()<br>// 7. bark() prints: &quot;Buddy says: Woof!&quot;<br>// 8. Computer returns 0 (success)<br>// 9. Program ends<br><br>// =============================================<br>// OUTPUT:<br>// =============================================<br><br>// Buddy says: Woof!</pre><h3>Summary</h3><ul><li>Data: What the program knows.</li><li>Action: What the program does.</li><li>Object: Data + Actions bundled together.</li><li>Paradigm: The big-picture approach to structuring code.</li><li>Class: Blueprint for creating objects.</li></ul><h3>Next in C++ Shots: 2 — Public &amp; Private</h3><p>We’ll learn how to protect your data from misuse.</p><blockquote><em>Keep coding. Keep shooting.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc99cf10780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL for Absolute Beginners: What You Actually Need to Know]]></title>
            <link>https://medium.com/@kodarpiece/mysql-for-absolute-beginners-what-you-actually-need-to-know-cfa272427e1f?source=rss-61b1dad63258------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa272427e1f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kodarpiece]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Kodar piece]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 17:53:06 GMT</pubDate>
            <atom:updated>2026-06-08T17:53:06.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dd8RlSF_IdWnw7dGXI6Aag.png" /></figure><h3>What Even Is MySQL?</h3><p>Let’s start with the simplest definition possible.</p><p>MySQL is a free tool for storing and organizing data in structured tables (just like spreadsheets). You can add, search, change, or remove data whenever you need to. Many websites and apps you use every day rely on MySQL behind the scenes.</p><h3>Wait — What Does “SQL” Mean?</h3><p>You’ve probably heard the term SQL = <strong>S</strong>tructured <strong>Q</strong>uery <strong>L</strong>anguage (often pronounced “sequel”). Let’s break down what those three words actually mean:</p><ul><li><strong>S</strong>tructured → The data is organized in a predictable, table-like format with rows and columns (like a spreadsheet). This structure makes it easy to find specific information.</li><li><strong>Q</strong>uery → A fancy word for a question you ask the database. For example, “Show me all customers who live in Texas.”</li><li><strong>L</strong>anguage → A set of words and rules you use to communicate with the database.</li></ul><p>So Structured Query Language literally means: <em>a language for asking questions to structured data (tables)</em>. When you write something like SELECT name FROM users WHERE city = &#39;Austin&#39;, you&#39;re speaking SQL.</p><p>There are many other tools that exist besides MySQL. Oracle, Microsoft SQL Server, and PostgreSQL are popular examples.</p><p>But here’s the key: All of them understand the same standard SQL language.</p><p>The difference isn’t the language. It’s the tool you use to run that language.</p><p>Let me explain what that actually means.</p><h3>If the Language Exists, Why Are There So Many Tools?</h3><p>SQL is the language — like English. But you still need a tool (the actual software) to do the work.</p><p>A tool is the software that physically stores, organizes, and manages your data on a computer. It’s the engine that follows your SQL commands.</p><p>Different tools exist for different jobs, but the good news is: SQL is standard. If you learn SQL on MySQL, you can use that knowledge on Oracle, Microsoft SQL Server, or PostgreSQL with very little adjustment.</p><p>Think of it this way: SQL is like English. MySQL, Oracle, and Microsoft SQL Server are like different phones. You can say “call Mom” in English on any phone — the words are the same, even if the buttons look a little different.</p><h3>The Three Parts of SQL You Actually Need to Know</h3><p>SQL commands are divided into categories. Each category has a different job.</p><p>Some commands build things. Some change data. Some just ask questions.</p><p>SQL has five official categories, but as a beginner, you only need to focus on three:</p><h4>1. DDL (Data Definition Language) — The Architect</h4><ul><li><strong>What it does:</strong> Defines the structure of your data — creates, changes, or deletes tables.</li><li><strong>Commands:</strong> CREATE, ALTER, DROP</li><li><strong>Analogy:</strong> Drawing the blueprint of a house and building the rooms.</li></ul><h4>2. DML (Data Manipulation Language) — The Mover</h4><ul><li><strong>What it does:</strong> Adds, changes, or removes the actual data inside your tables.</li><li><strong>Commands:</strong> INSERT, UPDATE, DELETE</li><li><strong>Analogy: </strong>Moving furniture in and out of the rooms.</li></ul><h4>3. DQL (Data Query Language) — The Question-Asker</h4><ul><li><strong>What it does:</strong> Asks questions to retrieve data without changing anything.</li><li><strong>Commands</strong>: SELECT</li><li><strong>Analogy:</strong> Looking inside the rooms and asking “What’s in the closet?” without touching anything.</li></ul><p><em>(There are also DCL for security and TCL for transactions — just know they exist. You won’t need them for your first weeks.)</em></p><h3>Part 1: DDL — Building Your Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xlmkGda00IKynPgceZwaw.png" /></figure><h4>CREATE</h4><ul><li><strong>Role:</strong> Makes a new table from scratch.</li><li><strong>Example:</strong> CREATE TABLE users (id INT, name VARCHAR(50));</li></ul><h4>ALTER</h4><p>it does multiple things.</p><ul><li><strong>ADD:</strong> Adds a new column to an existing table.<br><strong>Example:</strong> ALTER TABLE users ADD age INT;</li><li><strong>DROP</strong>: Removes an existing column from a table.<br>Example: ALTER TABLE users DROP COLUMN age;</li><li><strong>MODIFY</strong>: Changes a column’s data type (e.g., from INT to BIGINT)<br><strong>Example:</strong> ALTER TABLE users MODIFY COLUMN id BIGINT;</li><li><strong>RENAME</strong>: Changes a column’s name<br><strong>Example:</strong> ALTER TABLE users RENAME COLUMN name TO full_name;</li></ul><h4>DROP</h4><ul><li><strong>Role:</strong> Deletes a table or database completely (gone forever).</li><li><strong>Example:</strong> DROP TABLE users;</li></ul><h4>TRUNCATE</h4><ul><li><strong>Role:</strong> Removes all data from a table but keeps the structure ready to reuse.</li><li><strong>Example:</strong> TRUNCATE TABLE users;</li></ul><h4>RENAME (table)</h4><ul><li><strong>Role:</strong> Changes the name of a table.</li><li><strong>Example:</strong> RENAME TABLE users TO customers;</li></ul><h3>Data Types: What Kind of Data Goes in Each Column?</h3><p>When you create a table, you must tell MySQL what type of data each column will hold. Think of it like labeling containers: “this jar holds jelly, that one holds pickles.”</p><h4>INT</h4><ul><li>Whole numbers (no decimals).</li><li><strong>Example</strong>: age INT, id INT.</li></ul><h4>VARCHAR</h4><ul><li>Text (short to medium length). The number is the maximum characters.</li><li><strong>Example:</strong> name VARCHAR(50) (up to 50 letters).</li></ul><h4>DATE</h4><ul><li>Calendar dates (Year-Month-Day format).</li><li><strong>Example:</strong> birthday DATE</li></ul><h4>DECIMAL</h4><ul><li>Numbers with decimals (money, measurements). First number = total digits, second = digits after decimal.</li><li><strong>Example:</strong> price DECIMAL(10,2) (10 total digits, 2 after decimal → like 1234567.89)</li></ul><h4>Quick Example</h4><pre>CREATE TABLE products (<br>    id INT,<br>    name VARCHAR(100),<br>    price DECIMAL(10,2),<br>    created_at DATE<br>);</pre><blockquote><em>Beginner tip: You don’t need to memorize all data types. </em><em>INT, </em><em>VARCHAR, </em><em>DATE, and </em><em>DECIMAL will cover most of your early projects.</em></blockquote><h3>What Is a Constraint?</h3><p>A constraint is a rule that limits what data can go into a column — like saying “age can’t be negative” or “email must be unique.”</p><h4>How to Add Constraints</h4><ul><li><strong>PRIMARY KEY:</strong> Uniquely identifies each row (no duplicates, no blanks)<br>Example: CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50));</li><li><strong>FOREIGN KEY</strong>: Links a column to another table’s primary key (prevents orphan data).<br>Example: CREATE TABLE orders (user_id INT, FOREIGN KEY (user_id) REFERENCES users(id));</li><li><strong>UNIQUE:</strong> Prevents duplicate values in a column.<br>Example: CREATE TABLE users (email VARCHAR(100) UNIQUE);</li><li><strong>NOT NULL:</strong> Prevents empty values in a column.<br>Example: CREATE TABLE users (name VARCHAR(50) NOT NULL);</li><li><strong>CHECK</strong>: Ensures values meet a condition.<br>Example: CREATE TABLE users (age INT CHECK (age &gt;= 0));</li></ul><h4>Add a Constraint to an Existing Table</h4><ul><li><strong>ADD:</strong> Adds a rule to a table that already exist.</li><li>Example: ALTER TABLE users ADD CONSTRAINT unique_email UNIQUE (email);</li></ul><h4>Remove a Constraint from an Existing Table</h4><ul><li><strong>DROP:</strong> Deletes an existing rule</li><li>Example: ALTER TABLE users DROP CONSTRAINT unique_email;</li></ul><blockquote><strong><em>Note:</em></strong><em> MySQL doesn’t let you “modify” constraints directly — you have to drop and re-add them.</em></blockquote><h3>Part 2: DML (Data Manipulation Language) — The Movers</h3><h4>INSERT</h4><ul><li><strong>Role:</strong> Adds new rows of data into a table.</li><li><strong>Example:</strong> INSERT INTO users (id, name, age) VALUES (1, &#39;John&#39;, 25);</li></ul><h4>UPDATE</h4><ul><li><strong>Role:</strong> Changes existing data in one or more rows.</li><li><strong>Example:</strong> UPDATE users SET age = 26 WHERE name = &#39;John&#39;;</li></ul><h4>DELETE</h4><ul><li><strong>Role:</strong> Removes one or more rows from a table.</li><li><strong>Example:</strong> DELETE FROM users WHERE name = &#39;John&#39;;</li></ul><blockquote><strong><em>Important note for beginners:</em></strong><em> Always use </em><em>WHERE with </em><em>UPDATE and </em><em>DELETE — otherwise you&#39;ll change or delete every row in the table.</em></blockquote><blockquote><strong><em>Without</em></strong> WHERE: UPDATE users SET age = 99; → <em>everyone becomes age 99</em><strong><em>.</em></strong></blockquote><blockquote><strong><em>With</em></strong> WHERE: UPDATE users SET age = 99 WHERE name = &#39;John&#39;; → <em>only John changes.</em></blockquote><h3>Part 3: DQL (Data Query Language) — The Question-Asker</h3><h4>SELECT</h4><ul><li><strong>Role:</strong> Retrieves data from one or more tables without changing anything.</li><li><strong>Example:</strong> SELECT name, age FROM users WHERE city = &#39;Austin&#39;;</li></ul><h4>SELECT with all columns</h4><ul><li><strong>Role:</strong> Retrieves every column from a table.</li><li><strong>Example:</strong> SELECT * FROM users;</li></ul><h4>SELECT with DISTINCT</h4><ul><li><strong>Role:</strong> Retrieves only unique values, removing duplicates</li><li><strong>Example:</strong> SELECT DISTINCT city FROM users;</li></ul><h4>SELECT with ORDER BY</h4><ul><li><strong>Role:</strong> Sorts the results (ascending or descending).</li><li><strong>Example:</strong> SELECT name, age FROM users ORDER BY age DESC;</li></ul><h4>SELECT with LIMIT (MySQL specific)</h4><ul><li><strong>Role:</strong> Limits how many rows are returned.</li><li><strong>Example:</strong> SELECT name FROM users LIMIT 5;</li></ul><h4>Adding More Filters: AND, OR, LIKE</h4><ul><li><strong>AND </strong>: Both conditions must be true.<br><strong>Example:</strong> SELECT * FROM users WHERE age &gt; 18 AND city = &#39;Austin&#39;;</li><li><strong>OR</strong>: At least one condition must be true.<br><strong>Example:</strong> SELECT * FROM users WHERE city = &#39;Austin&#39; OR city = &#39;Dallas&#39;;</li><li><strong>LIKE</strong>: Matches a pattern (% means any number of characters,_ means one character)<br><strong>Example:</strong> SELECT * FROM users WHERE name LIKE &#39;J%&#39;; (finds names starting with J).</li></ul><h3>Aggregate Functions</h3><p>An aggregate function takes many rows of data and squishes them down into a single number or value.</p><p>Instead of showing you every row one by one, it answers questions like “How many total?” “What’s the average?” or “What’s the highest?”.</p><p>For example, if you have 1,000 employees in a table and you want to know their average salary, you don’t want to scroll through 1,000 rows — you just want one number.</p><p>That’s what aggregate functions do: they summarize multiple rows into one answer.</p><h4>COUNT</h4><ul><li><strong>Role:</strong> Counts the number of rows.</li><li><strong>Example:</strong> SELECT COUNT(*) FROM users;</li></ul><h4>SUM</h4><ul><li><strong>Role:</strong> Adds up all values in a numeric column.</li><li><strong>Example:</strong> SELECT SUM(salary) FROM employees;</li></ul><h4>AVG</h4><ul><li><strong>Role:</strong> Calculates the average of a numeric column.</li><li><strong>Example:</strong> SELECT AVG(age) FROM users;</li></ul><h4>MAX</h4><ul><li><strong>Role:</strong> Finds the highest value in a column.</li><li><strong>Example:</strong> SELECT MAX(price) FROM products;</li></ul><h4>MIN</h4><ul><li><strong>Role:</strong> Finds the lowest value in a column.</li><li><strong>Example:</strong> SELECT MIN(price) FROM products;</li></ul><h4>GROUP BY</h4><ul><li><strong>Role:</strong> Groups rows that have the same value, so aggregate functions can be applied to each group.</li><li><strong>Example:</strong> SELECT city, COUNT(*) FROM users GROUP BY city;</li></ul><blockquote><em>Translation: “Count how many users live in each city”.</em></blockquote><h4>HAVING</h4><ul><li><strong>Role:</strong> Filters groups after GROUP BY (like WHERE but for groups, not individual rows).</li><li><strong>Example:</strong> SELECT city, COUNT(*) FROM users GROUP BY city HAVING COUNT(*) &gt; 5;</li></ul><blockquote><em>Translation: “Show me cities with more than 5 users”.</em></blockquote><h3>Keyword Priority (Execution Order)</h3><p>This is the actual order MySQL executes your query, not the order you write it:</p><p><strong>1st → FROM</strong> → Which table?</p><p><strong>2nd → WHERE</strong> → Filter rows (individual rows)</p><p><strong>3rd → GROUP BY</strong> → Group rows together</p><p><strong>4th → HAVING</strong> → Filter groups</p><p><strong>5th → SELECT</strong> → Pick columns</p><p><strong>6th → ORDER BY</strong> → Sort results</p><p><strong>7th → LIMIT</strong> → Limit rows returned</p><h4>Example Query</h4><pre>SELECT city, COUNT(*) as total<br>FROM users<br>WHERE age &gt;= 18<br>GROUP BY city<br>HAVING COUNT(*) &gt; 10<br>ORDER BY total DESC<br>LIMIT 5;</pre><p><strong>Execution Order in Your Head</strong></p><ol><li>FROM users → &quot;Look at the users table&quot;</li><li>WHERE age &gt;= 18 → &quot;Keep only adults&quot;</li><li>GROUP BY city → &quot;Group remaining rows by city&quot;</li><li>HAVING COUNT(*) &gt; 10 → &quot;Keep only cities with 11+ adults&quot;</li><li>SELECT city, COUNT(*) → &quot;Show city name and count&quot;</li><li>ORDER BY total DESC → &quot;Sort biggest first&quot;</li><li>LIMIT 5 → &quot;Show top 5 cities&quot;</li></ol><h4>Key Takeaway</h4><ul><li>WHERE filters rows before grouping</li><li>HAVING filters groups after grouping</li></ul><p>You can’t use aggregate functions (like COUNT()) in WHERE — that&#39;s what HAVING is for.</p><h3>JOINs</h3><h4>What is a JOIN?</h4><p>A JOIN is how you combine two or more tables together using a shared column (like an ID).</p><p>Instead of keeping all your data in one giant, messy table, databases split information into smaller, organized tables.</p><p>When you need data from both tables, you JOIN them.</p><p>For example, one table holds customer names, another holds their orders — a JOIN lets you see which customer bought what.</p><h4>INNER JOIN</h4><ul><li><strong>Role:</strong> Returns only rows that have matching values in both tables (no orphans).</li><li><strong>Example:</strong></li></ul><pre>SELECT users.name, orders.product FROM users INNER JOIN orders ON users.id = orders.user_id;</pre><h4>LEFT JOIN (or LEFT OUTER JOIN)</h4><ul><li><strong>Role:</strong> Returns all rows from the left table, plus matches from the right table — if no match, right columns show NULL.</li><li><strong>Example:</strong></li></ul><pre>SELECT users.name, orders.product FROM users LEFT JOIN orders ON users.id = orders.user_id;</pre><h4>RIGHT JOIN (or RIGHT OUTER JOIN)</h4><ul><li><strong>Role:</strong> Returns all rows from the right table, plus matches from the left table — if no match, left columns show NULL</li><li><strong>Example:</strong></li></ul><pre>SELECT users.name, orders.product FROM users RIGHT JOIN orders ON users.id = orders.user_id;</pre><h4>Visual Summary</h4><ul><li><strong>INNER JOIN →</strong> Only rows that match in both tables.</li><li><strong>LEFT JOIN →</strong> All left table rows + matches from right.</li><li><strong>RIGHT JOIN → </strong>All right table rows + matches from left</li></ul><h4>Simple Analogy</h4><ul><li><strong>INNER JOIN</strong> = People who have both a driver’s license AND a car (must have both).</li><li><strong>LEFT JOIN </strong>= All people, plus car info if they own one (some may have NULL).</li></ul><blockquote><em>Just INNER JOIN and LEFT JOIN cover 90% of real-world needs.</em></blockquote><h3>Final Takeaways</h3><ul><li>SQL is the language. MySQL is just one tool that speaks it.</li><li>Three categories do most of the work: DDL (build), DML (change), DQL (ask).</li><li>Always use WHERE with UPDATE and DELETE — or you’ll change everything.</li><li>WHERE filters rows. HAVING filters groups. You can’t use COUNT() in WHERE.</li><li>INNER JOIN and LEFT JOIN handle nearly every real-world need.</li><li>Start with INT, VARCHAR, DATE, DECIMAL. That’s enough for months.</li></ul><p>Now stop reading. Go create a table. Insert something. Ask a question. Break it. Fix it. That’s how you learn.</p><h3>End</h3><p>Questions? I am here.</p><p>— kodar piece.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa272427e1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>