<?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 Kabhilasha on Medium]]></title>
        <description><![CDATA[Stories by Kabhilasha on Medium]]></description>
        <link>https://medium.com/@k10abhilasha?source=rss-566dc85d03ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*waYBFRbQiVuJvMirRh9sJA.png</url>
            <title>Stories by Kabhilasha on Medium</title>
            <link>https://medium.com/@k10abhilasha?source=rss-566dc85d03ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@k10abhilasha/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[C++ Under the Hood: From Source Files to Linkage, Lifetime and Storage Duration]]></title>
            <link>https://medium.com/@k10abhilasha/c-under-the-hood-from-source-files-to-linkage-lifetime-and-storage-duration-b458e88bc48b?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/b458e88bc48b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 09:59:39 GMT</pubDate>
            <atom:updated>2026-10-15T09:59:39.970Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning C++, I had a fairly simple mental model:</p><pre>write .cpp<br>    ↓<br>compile<br>    ↓<br>  run</pre><p>It works as a beginner’s model.</p><p>But as soon as a C++ project contains multiple .cpp files, headers, global variables, static, extern, dynamic allocation, or templates, that model starts breaking down.</p><p>Questions start appearing:</p><ul><li>Why can I declare a function in a header and define it somewhere else?</li><li>Why does compiling one .cpp file sometimes produce an undefined reference?</li><li>Why does static mean different things depending on where I use it?</li><li>Why does a local variable disappear when I leave a block?</li><li>Why can a static local variable survive multiple function calls?</li><li>Is every local variable really on the stack?</li><li>Is every pointer on the heap?</li><li>What’s the difference between scope, lifetime, storage duration, and linkage?</li></ul><p>These aren’t separate random C++ facts.</p><p>They are connected.</p><p>This article builds one mental model for understanding them.</p><h3>1. First: What Happens to a .cpp File?</h3><p>Suppose we have:</p><pre>project/<br>├── main.cpp<br>├── counter.cpp<br>└── counter.hpp</pre><p>We’ll use this project throughout the article.</p><p>Our header:</p><pre>// counter.hpp<br><br>#pragma once<br>void increment();<br>int getCount();<br>extern int globalCount;</pre><p>Our implementation:</p><pre>// counter.cpp<br>#include &quot;counter.hpp&quot;<br>static int internalValue = 10;<br>int globalCount = 0;<br>void increment() {<br>    static int calls = 0;<br>    ++calls;<br>    ++globalCount;<br>}<br>int getCount() {<br>    return globalCount;<br>}</pre><p>And our program:</p><pre>// main.cpp<br><br>#include &lt;iostream&gt;<br>#include &quot;counter.hpp&quot;<br>int main() {<br>    increment();<br>    increment();<br>    std::cout &lt;&lt; getCount() &lt;&lt; &#39;\n&#39;;<br>    std::cout &lt;&lt; globalCount &lt;&lt; &#39;\n&#39;;<br>    return 0;<br>}</pre><p>At first glance, this is just three files.</p><p>But the compiler does not simply throw all three files together and compile them as one giant file.</p><p>The translation process is much more interesting.</p><h3>2. Source File vs Translation Unit</h3><p>This distinction is important.</p><p>A <strong>source file</strong> is what we normally think of as a .cpp file.</p><p>A <strong>translation unit</strong> is the result of processing that source file through the relevant preprocessing stages.</p><p>For example:</p><pre>// main.cpp<br>#include &quot;counter.hpp&quot;<br>int main() {<br>    increment();<br>}</pre><p>After preprocessing, the contents of counter.hpp have effectively been incorporated into the translation unit.</p><p>Conceptually, we can imagine something like:</p><pre>void increment();<br>int getCount();<br><br>extern int globalCount;<br>int main() {<br>    increment();<br>}</pre><p>That entire result is a translation unit.</p><p>counter.cpp produces another translation unit.</p><p>So our project becomes conceptually:</p><pre>main.cpp<br>   ↓<br>translation unit<br>   ↓<br>main.o<br><br><br><br>counter.cpp<br>   ↓<br>translation unit<br>   ↓<br>counter.o</pre><p>These translation units can be translated separately and later linked together.</p><p>This is the foundation for understanding declarations, definitions and linkage.</p><h3>3. The Compilation Pipeline</h3><p>A useful practical model is:</p><pre>                main.cpp<br>                    │<br>                    ▼<br>              Preprocessor<br>                    │<br>                    ▼<br>             Translation unit<br>                    │<br>                    ▼<br>                Compiler<br>                    │<br>                    ▼<br>                Assembly<br>                    │<br>                    ▼<br>               Assembler<br>                    │<br>                    ▼<br>                  main.o</pre><p>And separately:</p><pre>              counter.cpp<br>                    │<br>                    ▼<br>              Preprocessor<br>                    │<br>                    ▼<br>             Translation unit<br>                    │<br>                    ▼<br>                Compiler<br>                    │<br>                    ▼<br>                Assembly<br>                    │<br>                    ▼<br>               Assembler<br>                    │<br>                    ▼<br>                counter.o</pre><p>Finally:</p><pre>      main.o ───────────┐<br>                        │<br>       counter.o ───────┼──→ Linker → executable<br>                        │<br>       libraries ───────┘</pre><p>This is a <strong>useful implementation model</strong>, not an exact description of what every compiler internally does.</p><p>The C++ standard describes translation in terms of translation phases, and real compilers are free to combine or rearrange implementation steps as long as the required behavior is produced.</p><h3>4. The Preprocessor</h3><p>The preprocessor deals with things such as:</p><pre>#include<br>#define<br>#ifdef<br>#ifndef<br>#if<br>#endif</pre><p>For example:</p><pre>#include &quot;counter.hpp&quot;</pre><p>causes the header to be processed and incorporated into the translation unit.</p><p>You can inspect the preprocessed output using GCC:</p><pre>g++ -E main.cpp</pre><p>You’ll see a lot more than your own code because standard headers and their dependencies can be enormous.</p><p>The important mental model is:</p><pre>.cpp<br> ↓<br>preprocessing<br> ↓<br>preprocessed translation unit<br> ↓<br>compiler</pre><p>The preprocessor itself does not perform C++ semantic compilation. It operates in the earlier translation stages.</p><h3>5. Compilation Is Separate for Each Translation Unit</h3><p>This is one of the most useful things to understand.</p><p>We can explicitly compile our files:</p><pre>g++ -c main.cpp<br>g++ -c counter.cpp</pre><p>Now we have:</p><pre>main.o<br>counter.o</pre><p>The -c option tells GCC to compile/assemble but stop before linking.</p><p>We can then link them:</p><pre>g++ main.o counter.o -o program</pre><p>Or simply:</p><pre>g++ main.cpp counter.cpp -o program</pre><p>which asks the toolchain to compile the source files and then link the resulting object files.</p><h3>6. Why Does the Linker Need to Exist?</h3><p>Look at main.cpp:</p><pre>#include &quot;counter.hpp&quot;<br><br>int main() {<br>    increment();<br>}</pre><p>The compiler sees:</p><pre>void increment();</pre><p>So it knows that a function called increment exists and knows its type.</p><p>But the implementation is somewhere else:</p><pre>void increment() {<br>    // ...<br>}</pre><p>The compiler compiling main.cpp does not need to see that implementation in the same translation unit.</p><p>Instead, the generated object file contains a reference to the function.</p><p>Conceptually:</p><pre>main.o<br>  │<br>  │ &quot;I need increment()&quot;<br>  ▼<br>linker<br>  ▲<br>  │ &quot;I found increment() here&quot;<br>  │<br>counter.o</pre><p>The linker resolves those references.</p><p>If we compile only:</p><pre>g++ main.cpp -o program</pre><p>we can get an error similar to:</p><pre>undefined reference to `increment()&#39;</pre><p>because the definition isn’t available to the linker.</p><p>This is the first place where <strong>declaration vs definition</strong> becomes practically important.</p><h3>7. Declaration vs Definition</h3><p>A declaration tells the compiler:</p><blockquote><em>This entity exists.</em></blockquote><p>For example:</p><pre>void increment();</pre><p>That’s a declaration.</p><p>A definition provides the entity itself:</p><pre>void increment() {<br>    ++globalCount;<br>}</pre><p>That’s a definition.</p><p>A useful rule is:</p><blockquote><strong><em>Every definition is a declaration, but not every declaration is a definition.</em></strong></blockquote><p>For variables:</p><pre>extern int globalCount;</pre><p>is a declaration.</p><p>It says:</p><blockquote><em>There is an </em><em>int called </em><em>globalCount defined somewhere.</em></blockquote><p>The actual definition is:</p><pre>int globalCount = 0;</pre><p>This distinction becomes especially important when several translation units are involved.</p><h3>8. What Exactly Does extern Do?</h3><p>Consider:</p><pre>// counter.hpp<br>extern int globalCount;</pre><p>and:</p><pre>// counter.cpp<br>int globalCount = 0;</pre><p>The header declares the variable.</p><p>The .cpp file defines it.</p><p>Then main.cpp can use it:</p><pre>#include &quot;counter.hpp&quot;<br>int main() {<br>    globalCount = 10;<br>}</pre><p>There is only one globalCount object.</p><p>Conceptually:</p><pre>main.cpp<br>    │<br>    │ extern int globalCount<br>    ▼<br> linker<br>    ▲<br>    │<br>    │ int globalCount = 0<br>counter.cpp</pre><p>This is an example of <strong>external linkage</strong>.</p><h3>9. Now the Interesting Part: static</h3><p>The keyword static is one of those C++ keywords that causes disproportionate confusion because its meaning depends heavily on where it appears.</p><p>Consider:</p><pre>static int internalValue = 10;</pre><p>at namespace/file scope.</p><p>This gives the name internal linkage.</p><p>It means that this entity is associated only with that translation unit.</p><p>So if counter.cpp contains:</p><pre>static int internalValue = 10;</pre><p>another translation unit cannot simply refer to that same name as an external entity.</p><p>Conceptually:</p><pre>counter.cpp<br>    │<br>    └── internalValue<br>          │<br>          └── visible only within this translation unit</pre><p>This is different from:</p><pre>int globalCount = 0;</pre><p>which has external linkage in the usual namespace-scope case.</p><h3>10. static Inside a Function Is Different</h3><p>Now look at:</p><pre>void increment() {<br>    static int calls = 0;<br>    ++calls;<br>}</pre><p>This static does <strong>not</strong> mean the same thing as namespace-scope static.</p><p>Here, calls has:</p><ul><li>block scope</li><li>static storage duration</li><li>no linkage</li></ul><p>Most importantly, its lifetime is not tied to each invocation of increment().</p><p>Consider:</p><pre>increment();<br>increment();<br>increment();</pre><p>The value of calls progresses:</p><pre>first call:   0 → 1<br>second call:  1 → 2<br>third call:   2 → 3</pre><p>The variable isn’t recreated every time the function is called.</p><p>It persists.</p><p>A block-scope static is initialized the first time control passes through its declaration, subject to the initialization rules. Since C++11, initialization of a local static is thread-safe.</p><h3>11. static Has Multiple Meanings — Don&#39;t Memorize One Definition</h3><p>This is a classic C++ interview trap.</p><p>Compare:</p><pre>static int x = 10;</pre><p>at namespace scope with:</p><pre>void foo() {<br>    static int x = 10;<br>}</pre><p>They both involve static storage duration, but their <strong>scope and linkage</strong> differ.</p><p>A useful comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Du5D7TuLw2gV0dArBjkZg.png" /></figure><p>C++20 also introduced module linkage, so modern C++ has more nuance than the old three-category “no/internal/external” model. For traditional header/.cpp code, however, those three are the core concepts to master first.</p><h3>12. Scope vs Linkage</h3><p>This distinction deserves its own section because it is easy to mix them up.</p><h3>Scope asks:</h3><blockquote><strong><em>Where can I use this name?</em></strong></blockquote><h3>Linkage asks:</h3><blockquote><strong><em>Can this name refer to the same entity across scopes/translation units?</em></strong></blockquote><p>For example:</p><pre>static int internalValue = 10;</pre><p>has namespace scope.</p><p>But its name has internal linkage, meaning it cannot be used to refer to that entity from another translation unit.</p><p>Meanwhile:</p><pre>void foo() {<br>    int x = 10;<br>}</pre><p>has block scope and no linkage.</p><p>The local name x belongs to that block.</p><p>So:</p><pre>Scope<br>  ↓<br>visibility of a name<br><br><br>Linkage<br>  ↓<br>relationship between declarations of an entity</pre><p>They answer different questions.</p><h3>13. Storage Duration</h3><p>Now we can move from <strong>names</strong> to <strong>objects</strong>.</p><p>C++ has four storage-duration categories:</p><pre>automatic<br>static<br>thread<br>dynamic</pre><p>These describe how long the storage associated with an object lasts.</p><h3>14. Automatic Storage Duration</h3><p>Consider:</p><pre>void foo() {<br>    int x = 10;<br>}</pre><p>x has automatic storage duration.</p><p>Its storage is associated with the execution of the block.</p><p>When execution leaves the block, the lifetime of the object ends and its destructor runs if it has one.</p><p>For a simple int, there is obviously no interesting destructor.</p><p>For:</p><pre>void foo() {<br>    std::string name = &quot;hello&quot;;<br>}</pre><p>the std::string object is destroyed when its lifetime ends.</p><p>We often say:</p><blockquote><em>“Local variables live on the stack.”</em></blockquote><p>That’s a useful implementation-level intuition.</p><p>But it is <strong>not a C++ language rule</strong>.</p><p>The C++ standard specifies storage duration and lifetime, not that every automatic object must physically reside on a stack. Optimizers can keep values in registers, eliminate objects, or otherwise transform the implementation as long as observable behavior is preserved.</p><h3>15. Static Storage Duration</h3><p>Now consider:</p><pre>int globalCount = 0;</pre><p>This has static storage duration.</p><p>The storage exists for the duration of the program.</p><p>A local static also has static storage duration:</p><pre>void increment() {<br>    static int calls = 0;<br>    ++calls;<br>}</pre><p>So even though calls has <strong>block scope</strong>, its storage persists for the lifetime of the program.</p><p>This is an excellent example of why:</p><blockquote><em>scope ≠ storage duration</em></blockquote><p>The name calls can only be used inside increment().</p><p>But the object itself persists between calls.</p><h3>16. Thread Storage Duration</h3><p>There is another category that is often forgotten:</p><pre>thread_local int value = 0;</pre><p>This gives the object <strong>thread storage duration</strong>.</p><p>Each thread gets its own instance.</p><p>Conceptually:</p><pre>Thread 1 → value = 10<br>Thread 2 → value = 20<br>Thread 3 → value = 30</pre><p>They are distinct objects.</p><h3>17. Dynamic Storage Duration</h3><p>Consider:</p><pre>int* p = new int(42);</pre><p>The dynamically allocated int has dynamic storage duration.</p><p>This is where our simple stack/heap model becomes useful.</p><p>We can think of it as:</p><pre>automatic storage<br>p<br>│<br>│ points to<br>▼<br>dynamic storage<br>┌─────────────┐<br>│      42     │<br>└─────────────┘</pre><p>The crucial point is:</p><blockquote><strong><em>The pointer and the pointed-to object are different objects.</em></strong></blockquote><p>For example:</p><pre>void foo() {<br>    int* p = new int(42);<br>}</pre><p>When foo() ends:</p><pre>p</pre><p>goes out of scope.</p><p>But the dynamically allocated int does <strong>not</strong> automatically disappear.</p><p>We have just created a memory leak.</p><p>This is one of the most important corrections to the simplistic statement:</p><blockquote><em>“When a pointer goes out of scope, the heap memory is freed.”</em></blockquote><p>It isn’t.</p><h3>18. new and delete</h3><p>When we write:</p><pre>Foo* p = new Foo();</pre><p>we are requesting dynamically allocated storage and creating a Foo object in that storage.</p><p>The constructor is invoked.</p><p>When we write:</p><pre>delete p;</pre><p>the object is destroyed and the storage is released.</p><p>The pairing is:</p><pre>new       → delete<br>new[]     → delete[]</pre><p>Do not mix:</p><pre>new    → free       ❌<br>malloc → delete     ❌</pre><h3>19. malloc Is Not the C++ Equivalent of new</h3><p>This distinction is important.</p><p>Suppose:</p><pre>class User {<br>public:<br>    User() {<br>        std::cout &lt;&lt; &quot;Constructor\n&quot;;<br>    }<br>  ~User() {<br>        std::cout &lt;&lt; &quot;Destructor\n&quot;;<br>    }<br>};</pre><p>Now:</p><pre>User* u = new User();</pre><p>will construct the User.</p><p>But:</p><pre>User* u = static_cast&lt;User*&gt;(std::malloc(sizeof(User)));</pre><p>only obtains raw storage.</p><p>It does not construct the User object.</p><p>Likewise:</p><pre>delete u;</pre><p>performs destruction followed by deallocation.</p><p>Whereas:</p><pre>std::free(u);</pre><p>only releases storage.</p><p>In modern C++, manually using malloc for ordinary objects is rarely what you want.</p><h3>20. The Heap Isn’t “An Array the CPU Searches”</h3><p>A common beginner explanation of dynamic allocation goes something like:</p><blockquote><em>The CPU maintains a free list and searches through it to find a sufficiently large block.</em></blockquote><p>That’s not the right mental model.</p><p>The allocator manages the bookkeeping associated with dynamic allocation.</p><p>Depending on the allocator and platform, it may use different data structures and strategies for managing free and allocated regions.</p><p>At a higher level:</p><pre>program<br>   ↓<br>new / malloc<br>   ↓<br>allocator<br>   ↓<br>OS virtual memory system<br>   ↓<br>physical memory</pre><p>The CPU executes the instructions involved in this process.</p><p>It isn’t itself maintaining the allocator’s free list.</p><h3>21. Initialization</h3><p>Now that we understand storage duration, initialization becomes much easier to reason about.</p><p>C++ supports several initialization forms.</p><p>For example:</p><pre>int a = 10;      // copy initialization<br>int b(10);       // direct initialization<br>int c{10};       // direct-list initialization<br>int d = {10};    // copy-list initialization</pre><p>Modern C++ code often favors braces:</p><pre>int x{10};</pre><p>because list initialization can prevent narrowing conversions.</p><p>For example:</p><pre>int x{3.14};     // error</pre><p>whereas:</p><pre>int x = 3.14;    // allowed, conversion occurs</pre><p>There is also default initialization:</p><pre>int x;</pre><p>For a local automatic int, this does not initialize it to zero. Reading its value before giving it a value results in undefined behavior.</p><p>This is one reason initialization should be taken seriously in C++.</p><h3>22. Initialization Depends on Storage Duration</h3><p>Compare:</p><pre>void foo() {<br>    int a;<br>    static int b;<br>}</pre><p>a is an automatic local variable.</p><p>b is a local static.</p><p>Their initialization behavior is different.</p><p>b has static storage duration and is initialized only once.</p><p>On subsequent calls to foo(), the declaration is not executed again in the ordinary sense.</p><p>This is why:</p><pre>void counter() {<br>    static int count = 0;<br>    ++count;<br>}</pre><p>can maintain state between calls.</p><h3>23. Object Lifetime vs Storage Duration</h3><p>This is a subtle distinction that becomes increasingly important in advanced C++.</p><p><strong>Storage duration</strong> describes the duration of the storage associated with an object.</p><p><strong>Lifetime</strong> describes the period during which an object actually exists as an object of its type.</p><p>These concepts are related but not identical.</p><p>For ordinary objects, they often appear to line up nicely:</p><pre>{<br>    std::string s{&quot;hello&quot;};<br>}</pre><p>But C++ also has advanced mechanisms involving:</p><ul><li>placement new</li><li>unions</li><li>object reuse</li><li>implicit object creation</li><li>lifetime extension</li><li>temporaries</li></ul><p>where storage can exist while the lifetime of a particular object within that storage has begun or ended.</p><p>You don’t need all of these mechanisms to understand basic C++, but knowing that <strong>storage and object lifetime are distinct concepts</strong> prevents many incorrect mental models later.</p><h3>24. Destruction Happens in Reverse Order</h3><p>Consider:</p><pre>void foo() {<br>    A a;<br>    B b;<br>    C c;<br>}</pre><p>Assuming these are ordinary automatic objects in the same scope, construction happens:</p><pre>A<br>B<br>C</pre><p>and destruction happens:</p><pre>C<br>B<br>A</pre><p>This is one of the foundations of <strong>RAII — Resource Acquisition Is Initialization</strong>.</p><p>Objects acquire resources during construction and release them during destruction.</p><p>That means we can use scope to manage resources automatically.</p><h3>25. This Is Why RAII Is So Powerful</h3><p>Instead of:</p><pre>void foo() {<br>    Resource* r = new Resource();<br>// lots of code<br>    delete r;<br>}</pre><p>modern C++ encourages:</p><pre>void foo() {<br>    auto r = std::make_unique&lt;Resource&gt;();<br>// lots of code<br>}</pre><p>When r leaves scope, its destructor automatically releases the resource.</p><p>Even if an exception occurs.</p><p>That is the real power of understanding lifetime.</p><p>C++ isn’t just about manually managing memory.</p><p>It’s about designing objects so that <strong>lifetime controls resource management</strong>.</p><h3>26. One Project, Many Concepts</h3><p>Let’s return to our example:</p><pre>// counter.hpp<br>#pragma once<br>void increment();<br>int getCount();<br>extern int globalCount;</pre><pre>// counter.cpp<br>#include &quot;counter.hpp&quot;<br>static int internalValue = 10;<br>int globalCount = 0;<br>void increment() {<br>    static int calls = 0;<br>    ++calls;<br>    ++globalCount;<br>}<br>int getCount() {<br>    return globalCount;<br>}</pre><pre>// main.cpp<br>#include &lt;iostream&gt;<br>#include &quot;counter.hpp&quot;<br>int main() {<br>    increment();<br>    increment();<br>    std::cout &lt;&lt; getCount() &lt;&lt; &#39;\n&#39;;<br>    std::cout &lt;&lt; globalCount &lt;&lt; &#39;\n&#39;;<br>}</pre><p>Now we can ask several questions.</p><h3>globalCount</h3><pre>int globalCount = 0;</pre><p>It has:</p><pre>namespace scope<br>static storage duration<br>external linkage</pre><h3>internalValue</h3><pre>static int internalValue = 10;</pre><p>It has:</p><pre>namespace scope<br>static storage duration<br>internal linkage</pre><h3>calls</h3><pre>static int calls = 0;</pre><p>It has:</p><pre>block scope<br>static storage duration<br>no linkage</pre><h3>increment</h3><pre>void increment();</pre><p>in the header is a declaration.</p><p>Its implementation:</p><pre>void increment() {<br>    ...<br>}</pre><p>in counter.cpp is its definition.</p><h3>main</h3><pre>int main()</pre><p>is the program’s entry point in the hosted C++ environment.</p><p>And all these pieces eventually have to coexist in the final program.</p><h3>27. The Four Questions I Now Ask About a C++ Object</h3><p>When I see a variable or function, instead of memorizing isolated rules, I ask:</p><blockquote>1. What is its scope?</blockquote><blockquote>Where is its name visible?</blockquote><blockquote>2. What is its linkage?</blockquote><blockquote>Can declarations in other scopes or translation units refer to the same entity?</blockquote><blockquote>3. What is its storage duration?</blockquote><blockquote>How long does the associated storage last?</blockquote><blockquote>4. What is its lifetime?</blockquote><blockquote>During what period does the object actually exist?</blockquote><blockquote>And separately:</blockquote><blockquote>5. How is it initialized?</blockquote><blockquote>How does the object acquire its initial state?</blockquote><p>This framework is much more useful than simply memorizing:</p><blockquote><em>local = stack<br>global = heap<br>pointer = heap</em></blockquote><h3>28. The Mental Model</h3><p>At the build-system/toolchain level:</p><pre>                    SOURCE FILES<br>                         │<br>                         ▼<br>                  PREPROCESSING<br>                         │<br>                         ▼<br>                TRANSLATION UNITS<br>                         │<br>                         ▼<br>                    COMPILATION<br>                         │<br>                         ▼<br>                   OBJECT FILES<br>                         │<br>                         ▼<br>                      LINKER<br>                         │<br>                         ▼<br>                    EXECUTABLE</pre><p>At the C++ language level:</p><pre>C++ ENTITY<br>                        │<br>        ┌───────────────┼────────────────┐<br>        ▼               ▼                ▼<br>      SCOPE          LINKAGE       STORAGE DURATION<br>        │               │                │<br>        │               │                ├── automatic<br>        │               │                ├── static<br>        │               │                ├── thread<br>        │               │                └── dynamic<br>        │               │<br>        │               ├── no linkage<br>        │               ├── internal<br>        │               ├── external<br>        │               └── module<br>        │<br>        ▼<br>   name visibility<br>                        │<br>                        ▼<br>                     LIFETIME<br>                        │<br>                        ▼<br>                  INITIALIZATION<br>                        │<br>                        ▼<br>                    DESTRUCTION</pre><p>These aren’t independent topics.</p><p>They describe different dimensions of what happens to an entity in a C++ program.</p><blockquote><em>C++ source files are processed into translation units. Translation units can be compiled separately into object files, and the linker combines those object files and resolves references between them. A declaration tells the compiler about an entity, while a definition provides it. Scope determines where a name can be used, while linkage determines how declarations can refer to the same entity across scopes and translation units. Storage duration describes how long storage associated with an object exists, while lifetime describes when the object itself exists. C++ has automatic, static, thread, and dynamic storage durations.</em></blockquote><h3>Final Takeaway</h3><p>The most useful shift in thinking is this:</p><pre>                  DON&#39;T THINK<br>      &quot;Where does this variable live?&quot;<br>                       ↓<br>                THINK ABOUT<br>       ┌────────────────────────┐<br>       │ Scope                  │<br>       │ Where is the name      │<br>       │ visible?               │<br>       ├────────────────────────┤<br>       │ Linkage                │<br>       │ Can another translation│<br>       │ unit refer to it?      │<br>       ├────────────────────────┤<br>       │ Storage duration       │<br>       │ How long does its      │<br>       │ storage exist?         │<br>       ├────────────────────────┤<br>       │ Lifetime               │<br>       │ When does the object   │<br>       │ actually exist?        │<br>       ├────────────────────────┤<br>       │ Initialization         │<br>       │ How does it acquire    │<br>       │ its initial state?     │<br>       └────────────────────────┘</pre><p>Once these distinctions become natural, topics such as static, extern, namespaces, global variables, RAII, dynamic allocation, object lifetime, and multi-file programs stop looking like unrelated C++ trivia.</p><p>They become different pieces of the same model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b458e88bc48b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does delete[] Know How Many Objects to Destroy in C++?]]></title>
            <link>https://medium.com/@k10abhilasha/how-does-delete-know-how-many-objects-to-destroy-in-c-cce8dde8930f?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/cce8dde8930f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 13:04:54 GMT</pubDate>
            <atom:updated>2026-10-07T13:04:54.314Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider this:</p><pre>Widget* arr = new Widget[10];<br>delete[] arr;</pre><p>When we call delete[] arr, we only provide a pointer to the first element.</p><p>So how does the implementation know that there are <strong>10 objects</strong> that need to be destroyed?</p><p>The answer is: <strong>the C++ standard does not prescribe a particular mechanism for this.</strong></p><p>Different implementations can keep track of the number of elements in different ways.</p><p>Two useful conceptual models are:</p><ol><li><strong>Overallocation / Allocation Cookie (Metadata Header)</strong></li><li><strong>Associating the Allocation with Its Element Count</strong></li></ol><p>Let’s start with the allocation-cookie approach.</p><h3>Overallocation / The Allocation Cookie (Metadata Header)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*aF3eDP_pYLni3asT_XdHNg.png" /></figure><p>When we allocate an array using:</p><pre>Widget* arr = new Widget[n];</pre><p>the implementation needs storage for:</p><ul><li>n Widget objects</li><li>potentially some additional bookkeeping information</li></ul><p>One possible implementation is to store the number of elements in a hidden area associated with the allocation. This is commonly called an <strong>allocation cookie</strong>.</p><p>Conceptually, the memory could look like this:</p><pre>[ Hidden Metadata / Count ] [ Widget 0 ] [ Widget 1 ] ... [ Widget n-1 ]<br>                              ^<br>                              |<br>                    Pointer returned to your code<br>                              arr</pre><p>Notice that the pointer returned to our program points to the first element of the array, <strong>after</strong> the hidden metadata.</p><p>An implementation could conceptually do something similar to this:</p><pre>char* temp =<br>    static_cast&lt;char*&gt;(operator new[](WORDSIZE + n * sizeof(Widget)));<br>Widget* p = reinterpret_cast&lt;Widget*&gt;(temp + WORDSIZE);<br>*reinterpret_cast&lt;size_t*&gt;(temp) = n;<br>for (size_t i = 0; i &lt; n; ++i) {<br>    new (p + i) Widget();<br>}</pre><p>This is <strong>conceptual pseudocode</strong>, not code that the C++ standard requires an implementation to generate.</p><p>The actual implementation depends on the compiler, ABI, runtime, allocator, object type, and other implementation details.</p><h3>Line 1</h3><pre>char* temp =<br>    static_cast&lt;char*&gt;(operator new[](WORDSIZE + n * sizeof(Widget)));</pre><p>WORDSIZE represents the amount of space reserved for our hypothetical metadata.</p><p>For example, an implementation might reserve 4 or 8 bytes, but there is <strong>no requirement</strong> that it do so.</p><p>The actual size and layout of an allocation cookie are implementation-specific.</p><p>operator new[] is an allocation function. It receives the amount of storage to allocate in <strong>bytes</strong>, rather than simply receiving the number of array elements.</p><p>In this conceptual example, we request enough space for:</p><pre>metadata + n × sizeof(Widget)</pre><p>We use a char* here because pointer arithmetic on a char* moves in units of bytes.</p><h3>Line 2</h3><pre>Widget* p = reinterpret_cast&lt;Widget*&gt;(temp + WORDSIZE);</pre><p>At this point, temp points to the beginning of the allocated block.</p><p>We want p to point to the first Widget.</p><p>So we move forward by WORDSIZE bytes, past the hypothetical cookie:</p><pre>temp<br>  |<br>  v<br>[ Cookie ][ Widget 0 ][ Widget 1 ] ... [ Widget n-1 ]<br>            ^<br>            |<br>            p</pre><p>Now p points to the first element of the array.</p><h3>Line 3</h3><pre>*reinterpret_cast&lt;size_t*&gt;(temp) = n;</pre><p>We store the number of elements, n, in our hypothetical metadata area.</p><p>Later, when delete[] is used, the implementation could retrieve this information.</p><h3>Lines 4–6</h3><pre>for (size_t i = 0; i &lt; n; ++i) {<br>    new (p + i) Widget();<br>}</pre><p>Now we need to construct the objects in the allocated storage.</p><p>For each element, we use <strong>placement new</strong> to construct a Widget at the appropriate memory location.</p><p>For a class type such as Widget, this invokes its constructor.</p><p>The important point is that we now have n actual Widget objects living in the allocated storage.</p><h3>What Happens When We Call delete[]?</h3><p>Now consider:</p><pre>delete[] arr;</pre><p>If the implementation used an allocation cookie, it could conceptually do something like this:</p><pre>size_t n =<br>    *reinterpret_cast&lt;size_t*&gt;(<br>        static_cast&lt;char*&gt;(static_cast&lt;void*&gt;(p)) - WORDSIZE<br>    );<br>while (n != 0) {<br>    --n;<br>    (p + n)-&gt;~Widget();<br>}<br>operator delete[](static_cast&lt;char*&gt;(static_cast&lt;void*&gt;(p)) - WORDSIZE);</pre><p>Again, this is <strong>only a conceptual representation</strong>.</p><p>The compiler is not required to generate this exact sequence of operations.</p><h3>Line 1</h3><p>Conceptually:</p><pre>size_t n = /* read the cookie */;</pre><p>The implementation retrieves the number of elements from the metadata.</p><p>In our simplified model, it does this by moving backward from p by WORDSIZE bytes.</p><p>The important idea is:</p><pre>[ Cookie ][ Widget 0 ][ Widget 1 ] ... [ Widget n-1 ]<br>    ^       ^<br>    |       |<br>    n is     p/arr<br>stored here</pre><p>So the implementation can recover the element count even though the user only has the pointer arr.</p><h3>Lines 2–4</h3><pre>while (n != 0) {<br>    --n;<br>    (p + n)-&gt;~Widget();<br>}</pre><p>Once the implementation knows the number of elements, it can destroy them.</p><p>The destructors are called in <strong>reverse order</strong>:</p><pre>Widget n-1<br>Widget n-2<br>...<br>Widget 1<br>Widget 0</pre><p>This is important for arrays of objects with non-trivial destructors.</p><p>For example:</p><pre>Widget* arr = new Widget[10];</pre><pre>delete[] arr;</pre><p>The implementation needs to destroy all 10 Widget objects before releasing their storage.</p><p>This is one of the reasons an implementation may need to keep track of the number of elements.</p><p>For a trivially destructible type such as int, there are no destructor calls that need to be performed. The implementation still has to correctly handle the allocation, but it does not need to invoke 10 int destructors.</p><h3>Final step</h3><p>After the objects have been destroyed, the implementation releases the allocated storage.</p><p>Conceptually:</p><pre>operator delete[](/* original allocation */);</pre><p>In our simplified cookie model, the original allocation begins at the address where the cookie was stored, rather than at p.</p><p>So the conceptual sequence is:</p><pre>1. Find the metadata.<br>2. Read the element count.<br>3. Destroy the objects in reverse order.<br>4. Release the allocated storage.</pre><h3>Visualizing the Whole Process</h3><h3>Allocation</h3><pre>              arr / p<br>               |<br>               v<br>[ Cookie ][ Widget 0 ][ Widget 1 ][ Widget 2 ] ... [ Widget n-1 ]<br>    ^<br>    |<br> element count</pre><h3>Deallocation</h3><pre>              arr / p<br>                |<br>                v<br>[ Cookie ][ Widget 0 ][ Widget 1 ][ Widget 2 ] ... [ Widget n-1 ]<br>    ^<br>    |<br>1. Read count<br>        ↓<br>2. Destroy Widget n-1<br>        ↓<br>3. Destroy Widget n-2<br>        ↓<br>       ...<br>        ↓<br>4. Destroy Widget 0<br>        ↓<br>5. Release the allocation</pre><p>The important point is that <strong>the cookie is an implementation technique, not a feature specified by the C++ language</strong>.</p><h3>Associating the Array Size with the Allocation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*B4trawPTT_7krJRYEvif_A.png" /></figure><p>The allocation-cookie approach stores the element count <strong>next to the array in memory</strong>.</p><p>But an implementation could conceptually keep this information somewhere else.</p><p>For example, imagine that the implementation maintains an internal table that associates an allocation’s address with its element count:</p><pre>Array:<br>[ Widget 0 ][ Widget 1 ] ... [ Widget n-1 ]<br>      ^<br>      |<br>     arr<br><br>Internal association:<br>+----------------+-------+<br>| Allocation     | Count |<br>+----------------+-------+<br>| arr            |   n   |<br>+----------------+-------+</pre><p>The array itself does not contain the count.</p><p>Instead, the implementation maintains the association separately.</p><p>Conceptually, allocation could look something like:</p><pre>Widget* p =<br>    static_cast&lt;Widget*&gt;(operator new[](n * sizeof(Widget)));<br>for (size_t i = 0; i &lt; n; ++i) {<br>    new (p + i) Widget();<br>}<br>associationTable.insert(p, n);</pre><p>The important operation is:</p><pre>associationTable.insert(p, n);</pre><p>It records that the allocation beginning at address p contains n elements.</p><p>Later, when:</p><pre>delete[] p;</pre><p>is called, the implementation could conceptually do:</p><pre>size_t n = associationTable.lookup(p);<br>while (n != 0) {<br>    --n;<br>    (p + n)-&gt;~Widget();<br>}<br>associationTable.erase(p);<br>operator delete[](p);</pre><p>The process would therefore be:</p><ol><li>Look up the allocation in the internal association.</li><li>Retrieve the number of elements.</li><li>Destroy the elements in reverse order.</li><li>Remove the association.</li><li>Release the allocated storage.</li></ol><p>The important difference is <strong>where the metadata lives</strong>.</p><h3>Allocation Cookie</h3><pre>[ Metadata ][ Array ]<br>      ^<br>      |<br> stored alongside<br> the allocation</pre><h3>External Association</h3><pre>[ Array ]<br>    ^<br>    |<br>    +----------------------+<br>                           |<br>                           v<br>                 Internal association<br>                 +-------------+<br>                 | address: n  |<br>                 +-------------+</pre><p>This is again a <strong>conceptual model</strong>, not a requirement of the C++ standard.</p><p>A real implementation does not have to use a C++ map or hash table like the one shown above.</p><p>The implementation is free to use whatever mechanism allows it to provide the required behavior.</p><h3>So, Does delete[] Actually Know the Size?</h3><p>Not necessarily in the way we might first imagine.</p><p>There are actually two related questions:</p><p><strong>1. How does the implementation know how many objects need to be destroyed?</strong></p><p>For non-trivially destructible objects, it needs some way to obtain the necessary information.</p><p><strong>2. How does the memory allocator know how much storage to release?</strong></p><p>That is a separate concern.</p><p>The underlying allocator may have its own bookkeeping mechanism for tracking the size of an allocation.</p><p>Therefore, it is more accurate to think of delete[] as needing to correctly handle the <strong>array of objects</strong>, while the details of how the implementation and allocator track storage are implementation-specific.</p><p>The C++ standard specifies the required behavior of new[] and delete[], but it does <strong>not</strong> require a particular memory layout, allocation cookie, lookup table, or other bookkeeping mechanism.</p><p>And that’s the interesting part:</p><blockquote><strong><em>You give </em></strong><strong><em>delete[] only a pointer, but the implementation can still correctly destroy the array because it has implementation-specific ways of associating that pointer with the information it needs.</em></strong></blockquote><p>That hidden bookkeeping is what makes the seemingly simple line</p><pre>delete[] arr;</pre><p>much more interesting under the hood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cce8dde8930f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Pointers : Auto pointers and Unique pointers]]></title>
            <link>https://medium.com/@k10abhilasha/smart-pointers-auto-pointers-and-unique-pointers-90ec985137ba?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/90ec985137ba</guid>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 10:46:43 GMT</pubDate>
            <atom:updated>2026-01-13T10:46:43.690Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Role of Pointers in C++</strong></p><p>Pointers are a fundamental feature of C++ as they provide direct and fine-grained control over memory and system resources.</p><p><strong>Challenges with Raw Pointers</strong></p><p>When misused, raw pointers can lead to serious issues such as memory leaks, dangling pointers, double deletions, and undefined behaviour that may even crash a program. The difficulty lies in the fact that the programmer is fully responsible for manually managing the lifetime of the objects a pointer refers to. This manual management is error-prone and often the source of subtle, hard-to-diagnose bugs.</p><p><strong>Smart Pointers: A Modern Solution</strong></p><p>Modern C++ addresses these challenges with smart pointers, class templates that wrap raw pointers and manage resource ownership automatically. By ensuring that dynamically allocated objects are destroyed when no longer needed, smart pointers eliminate many common errors in memory and resource management, while still giving developers the flexibility of pointer semantics. Smart pointers are defined in the &lt;memory&gt; header. Smart pointers deliberately do not support pointer arithmetic because they model ownership of a single resource rather than acting as raw memory addresses.</p><h3>Auto Pointers</h3><p>Auto pointer was an early C++ smart pointer. It manages the lifetime of an object by destroying the managed object when auto_ptr is destroyed. auto_ptr works on an exclusive ownership basis i.e., only one object can point to a memory location. The ownership can be transferred on copying, but it can cause unexpected behaviour and bugs as it simulates move semantics using copy semantics, which is unsafe and unintuitive.</p><p>It manages memory by releasing the memory when the pointer goes out of scope. In this way even if an exception occurs before the block ends, the destructor gets called and the memory is freed.</p><p><strong>Syntax</strong>:</p><pre>std::auto_ptr&lt;Type&gt; ptr(new Type());</pre><p>Example</p><pre>class A{<br>//Some implementation <br>};<br><br>int main(){<br>    std::auto_ptr&lt;int&gt; ptr(new int(20));<br>    std::auto_ptr&lt;A&gt; Aptr (new A());<br>}</pre><p><strong>Limitations</strong>:</p><ol><li>auto_ptr cannot be used with standard containers because containers copy elements internally and copying an auto_ptr transfers ownership.</li><li>auto_ptr neither supports arrays nor custom deleters because it always deletes the managed object using delete and provides no mechanism to specify a custom deletion strategy.</li><li>Copying leaves the old pointers as NULL, which may cause logical errors when transferring ownership.</li></ol><pre>std::auto_ptr&lt;int&gt; p1(new int(10));<br>std::auto_ptr&lt;int&gt; p2 = p1; // ownership transferred<br>// p1 == nullptr</pre><p>Danger :</p><ul><li>Using p1 assuming it still owns the object.</li><li>Silent loss of ownership (very non-intuitive).</li></ul><p>Because of all these reasons, auto_ptr was deprecated and later removed from C++ 17 to be replaced by unique pointers, shared pointers and weak pointers. Although the main replacement is unique pointers.</p><h3><strong>Unique pointers</strong></h3><p>Unique pointer is one of the smart pointers and it works on single ownership basis i.e., only one object can point to a memory block. The ownership can be transferred however to another pointer by using move semantics. It releases the owned resource when it goes out of scope, as its destructor automatically deletes the managed object.</p><p><strong>Syntax:</strong></p><pre>std::unique_ptr&lt;type&gt; variable_name (new type());</pre><pre>std::unique_ptr&lt;type&gt; name = std::make_unique&lt;type&gt;();</pre><blockquote>The first syntax explicitly allocates memory using new and then transfers ownership to the std::unique_ptr. While this works, it is not exception-safe in complex expressions.<br><br>Consider the following function call:</blockquote><pre>foo(std::unique_ptr&lt;T&gt;(new T()), mayThrow());</pre><blockquote>If:</blockquote><blockquote>- new T() succeeds, and<br>- mayThrow() throws an exception before the unique_ptr is fully constructed,</blockquote><blockquote>This issue occurs because, prior to C++17, the order of evaluation of function arguments was unspecified. If new T() succeeds and mayThrow() throws before the unique_ptr constructor is entered, the raw pointer is leaked since no smart pointer has taken ownership.</blockquote><blockquote>But in second syntax</blockquote><blockquote>std::make_unique performs allocation and construction in a single, atomic operation and immediately returns a fully constructed std::unique_ptr.</blockquote><blockquote>Why This Is Better<br>- Guarantees exception safety<br>- Prevents memory leaks in complex expressions<br>- Avoids exposing raw pointers altogether<br>- Produces clearer and more readable code<br>- If an exception is thrown during object construction, the allocated memory is automatically deallocated, ensuring no resource leaks.</blockquote><blockquote>std::unique_ptr fully supports custom deleters.<br>However, std::make_unique cannot be used when a custom deleter is required because the deleter type must be specified as part of the unique_ptr type.</blockquote><p><strong>Unique pointer Vs Auto pointer</strong></p><p>Auto pointer implements ownership transfer using its copy constructor not a move constructor</p><pre>auto_ptr(auto_ptr&amp; other) :ptr(other.ptr){<br>        other.ptr=nullptr; //destructive copy<br>}</pre><p>what it means:</p><ul><li>when auto_ptr is copied, it steals the raw pointer.</li><li>The source is nulled out.</li><li>Both pointers do not point to the same resource.</li><li>But the compiler thinks it performed a normal copy.</li></ul><p>Why this breaks code:</p><p>Because the compiler believes auto_ptr is copyable, it uses the copy constructor in many places:</p><ul><li>Passing the value</li><li>Returning the value</li><li>Vector allocation</li><li>Algorithm operations (Sort, Swap, remove_if, etc.)</li></ul><p>Each of these triggers ownership transfer, leaving objects empty unexpectedly. This leads to :</p><ul><li>Memory leak: ownership moved during an unnoticed copy-&gt; no object deletes the pointer-&gt; leak.</li><li>Dangling access: A function receives an auto_ptr by value -&gt; parameters steals resources -&gt; caller&#39;s pointer becomes null unexpectedly.</li></ul><p>All these have the same root cause auto_ptr abuses the copy construct for moves. This violates the fundamental rule: copies must not destroy the source.</p><p>C++ introduces move semantics and unique_ptr uses them correctly.</p><pre>unique_ptr (unique_ptr &amp;&amp; other) noexcept : ptr(other.ptr){<br>           other.ptr = nullptr; //destructive move<br>}</pre><ul><li>Move constructor (rvalue reference): The constructor accepts only rvalues (temporaries), not lvalues, ensuring that ownership transfer is always explicit and intentional.</li><li>Copy constructor is deleted:This forces the compiler to treat unique_ptr as non-copyable and it can only be transferred explicitly using std::move.</li><li>STL containers use move, not copy with unique_ ptr C++ containers first try move constructor fall back to copy constructor if move unavailable. Since unique_ptr has only move constructor containers never copy it only move it.This eliminates all the auto_ptr problems.</li></ul><h4><em>Best practices</em></h4><blockquote>- Use make_unique instead of new</blockquote><blockquote>- Pass by reference if ownership is changing</blockquote><pre>void fun(unique_ptr&lt;A&gt;&amp;p) // can modify caller&#39;s ptr<br>void func(const unique_ptr&lt;A&gt; &amp;p) //read-only access<br></pre><ul><li>unique_ptr works well with RAII and factory patterns</li><li>Internally, std::unique_ptr stores the managed pointer and its deleter. When the deleter is empty, implementations use Empty Base Optimization (EBO), so the unique_ptr occupies no extra space beyond the raw pointer.</li><li>Adding deleters changes the type of unique_ptr as deleter is part of the unique_ptr type.</li></ul><pre>using P1 = std::unique_ptr&lt;A&gt;<br>using P2 = std::unique_ptr&lt;A, Deleter&gt;;<br>static_assert(!std::is_same_v&lt;P1, P2&gt;);</pre><ul><li>unique_ptr move operations are faster than shared_ptr refcount operations .</li><li>unique_ptr supports polymorphism safely as long as the base destructor is virtual.</li></ul><pre>std::unique_ptr&lt;Base&gt; p = std::make_unique&lt;Derived&gt;();</pre><p><strong>Important methods available in unique_ptr</strong></p><ul><li>get() → returns raw pointer without releasing ownership</li><li>release() → releases ownership and returns raw pointer (caller must delete)</li><li>reset() → deletes current object and optionally takes ownership of a new one</li></ul><pre>std::unique_ptr&lt;A&gt; p = std::make_unique&lt;A&gt;();<br>A* raw = p.get();      // no ownership transfer<br>A* raw2 = p.release(); // ownership released, p == nullptr<br>p.reset(new A());      // deletes old, owns new</pre><h4><strong>Examples</strong></h4><ol><li><strong>Basic ownership and automatic cleanup (RAII)</strong></li></ol><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br>class Resource {<br>public:<br>    Resource()  { std::cout &lt;&lt; &quot;Resource acquired\n&quot;; }<br>    ~Resource() { std::cout &lt;&lt; &quot;Resource released\n&quot;; }<br>};<br>int main() {<br>    {<br>        std::unique_ptr&lt;Resource&gt; ptr = std::make_unique&lt;Resource&gt;();<br>        // ptr owns the resource<br>    }<br> // ptr goes out of scope here<br>}</pre><ul><li>std::unique_ptr enforces single ownership of the resource.</li><li>When ptr goes out of scope, its destructor is invoked.</li><li>The destructor automatically deletes the managed object.</li></ul><p><strong>2</strong>. <strong>Ownership Transfer Using Move Semantics</strong></p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br>void consume(std::unique_ptr&lt;int&gt; p) {<br>    std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *p &lt;&lt; &quot;\n&quot;;<br>}<br>int main() {<br>    std::unique_ptr&lt;int&gt; ptr = std::make_unique&lt;int&gt;(10);<br>    consume(std::move(ptr));   // ownership transferred<br>    if (!ptr) {<br>        std::cout &lt;&lt; &quot;ptr no longer owns the resource\n&quot;;<br>    }<br>}</pre><ul><li>unique_ptr cannot be copied.</li><li>Ownership transfer must be explicit using std::move.</li><li>After the move:</li></ul><p>-&gt; ptr becomes nullptr</p><p>-&gt; consume() owns the resource</p><p><strong>3</strong>. <strong>Passing unique_ptr Correctly to Functions</strong></p><p><strong><em>ownership transfer</em></strong></p><pre>void process(std::unique_ptr&lt;A&gt; p); // takes ownership</pre><p>Calling this function destroys ownership in the caller, often unintentionally.</p><p><strong><em>read-only access</em></strong></p><pre>void readOnly(const std::unique_ptr&lt;A&gt;&amp; p) {<br>    p-&gt;doWork();<br>}</pre><p><strong><em>Modify caller’s pointer</em></strong></p><pre>void reset(std::unique_ptr&lt;A&gt;&amp; p) {<br>    p = std::make_unique&lt;A&gt;();<br>}</pre><p><strong>4</strong>. <strong>Custom Deleter Example</strong></p><pre>#include &lt;cstdio&gt;<br>#include &lt;memory&gt;<br>struct FileCloser {<br>    void operator()(FILE* f) const {<br>        if (f) std::fclose(f);<br>    }<br>};<br>int main() {<br>    std::unique_ptr&lt;FILE, FileCloser&gt; file(std::fopen(&quot;data.txt&quot;, &quot;w&quot;));<br>    if (file) {<br>        std::fputs(&quot;Hello\n&quot;, file.get());<br>    }<br>}</pre><ul><li>make_unique cannot deduce custom deleter types</li><li>Deleter must be specified explicitly</li><li>FILE* must be closed using fclose, not delete</li><li>unique_ptr supports custom deleters</li><li>Deleter becomes part of the pointer’s type</li></ul><pre>std::unique_ptr&lt;FILE, FileCloser&gt;</pre><p><strong>5. Minimal custom unique_ptr</strong></p><pre>template &lt;typename T&gt;<br>class UniquePtr {<br>    T* ptr;<br>public:<br>    explicit UniquePtr(T* p = nullptr) : ptr(p) {}<br>    // Disable copy<br>    UniquePtr(const UniquePtr&amp;) = delete;<br>    UniquePtr&amp; operator=(const UniquePtr&amp;) = delete;<br>    // Enable move<br>    UniquePtr(UniquePtr&amp;&amp; other) noexcept : ptr(other.ptr) {<br>        other.ptr = nullptr;<br>    }<br>    UniquePtr&amp; operator=(UniquePtr&amp;&amp; other) noexcept {<br>        if (this != &amp;other) {<br>            delete ptr;<br>            ptr = other.ptr;<br>            other.ptr = nullptr;<br>        }<br>        return *this;<br>    }<br>    T* get() const { return ptr; }<br>    ~UniquePtr() {<br>        delete ptr;<br>    }<br>};</pre><p>Raw pointers give C++ its power, but they also place the burden of correct lifetime management entirely on the programmer. auto_ptr was an early attempt to reduce this burden, but its design relied on implicit ownership transfer through copy semantics. This violated fundamental expectations about copying and led to subtle bugs, especially when used with functions, containers, and standard algorithms.</p><p>std::unique_ptr corrects these issues by making ownership explicit and unambiguous. Copying is disallowed, ownership transfer is performed only through move semantics, and resource cleanup is guaranteed through RAII. As a result, unique_ptr integrates safely with modern C++ features, including exception handling, STL containers, and generic code, without the surprising behavior that plagued auto_ptr.</p><p>In modern C++, unique_ptr should be the default choice whenever exclusive ownership of a dynamically allocated resource is required. It expresses intent clearly in the type system, prevents accidental ownership loss at compile time, and eliminates an entire class of memory management errors.<br>Understanding the limitations of auto_ptr and the design decisions behind unique_ptr provides a solid foundation for reasoning about more complex ownership models. This naturally leads to shared ownership, reference counting, and the need for weak_ptr, which will be discussed next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90ec985137ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointer in C++: Function Pointers]]></title>
            <link>https://medium.com/@k10abhilasha/pointer-in-c-function-pointers-471908aa4c0e?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/471908aa4c0e</guid>
            <category><![CDATA[function-pointer]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 11:51:01 GMT</pubDate>
            <atom:updated>2025-09-20T11:51:49.415Z</atom:updated>
            <content:encoded><![CDATA[<p>When we think of pointers in C++, we usually picture them pointing to data — integers, structs, arrays. But did you know pointers can also point to <strong>functions</strong>?</p><p>Yes, a function itself lives in memory, and just like data, you can store its address in a pointer. This opens up a whole world of <strong>dynamic behavior</strong> in C++.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5HF3V6URk8E2gW_P51Eww.png" /></figure><p>In this post, we’ll explore:</p><ol><li>What function pointers are and how they work</li><li>Real-world use cases (event handling, plugins, async programming)</li><li>Rules and gotchas</li><li>Arrays of function pointers</li><li>Casting</li><li>Static V/S Non-Static member function</li></ol><h3>1. Function Pointer</h3><p>A function pointer is a special type of pointer which <strong>stores the address</strong> of a function . It can be declared as:</p><pre>(returnType) (*Variable Name) (arguments)</pre><p>Let&#39;s say there is a function which two integer arguments and return their sum as integer.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int Sum(int a, int b) { return a + b; }<br><br>int main() {<br>    // declare a pointer to a function taking (int, int) and returning int<br>    int (*fp)(int, int) = Sum;<br><br>    cout &lt;&lt; fp(2, 5) &lt;&lt; endl;       // 7<br>    cout &lt;&lt; (*fp)(3, 4) &lt;&lt; endl;    // 7 (equivalent)<br>}</pre><blockquote><strong>📝 Note :</strong></blockquote><blockquote>1. You can use Sum or &amp;Sum; both work because the function name decays to its address.</blockquote><blockquote>2. Calling via (*fp)(args) is equivalent to fp(args).</blockquote><h4>🔍 What happens under the hood?</h4><p>When you call a function via a pointer:</p><ol><li>The program fetches the function address stored in the pointer.</li><li>It sets the CPU’s instruction pointer to that address.</li><li>Execution jumps to the function body — just as if you called it directly.</li></ol><p>So the only difference is <strong>how you got there</strong>.</p><h3>2. Uses of function pointer</h3><p>Okay, storing function addresses is cool, but <em>why should you care</em>?</p><p>Function pointers shine when you want to <strong>call different functions dynamically</strong>, instead of hardcoding a chain of if-else or switch statements.</p><p>Let’s explore three classic use cases.</p><h3>2.1 Event Handling (Callbacks)</h3><p>When we have a lots of Events in our system, we register callback for each event Which in turn calls different function internally. This one of the most classical use cases of passing a function pointer to another function so it can callback when event happens or when it finishes something.</p><p>A <strong>callback</strong> is just a fancy way of saying: “<em>Hey, when this thing happens, call my function instead of your own.</em>”</p><p>Think of it like leaving your number with a restaurant: “<em>Call me when my table is ready</em>.” The restaurant (the event manager) doesn’t know what you’ll do when you get the call (maybe show up, maybe send a friend), it just promises to call back. It is basically someone else call your function later and decouples “when” something happens from “what to do”.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br><br>// --- Event Types ---<br>enum class EventType { BATTERY, WIFI };<br><br>// --- Handlers ---<br>void onBattery(const string&amp; msg) {<br>    cout &lt;&lt; &quot;[ALERT] Battery: &quot; &lt;&lt; msg &lt;&lt; endl;<br>}<br><br>void onWifi(const string&amp; msg) {<br>    cout &lt;&lt; &quot;[LOG] WiFi: &quot; &lt;&lt; msg &lt;&lt; endl;<br>}<br><br>// --- Event Manager using Function Pointers ---<br>class EventManager {<br>private:<br>    void (*handlers[2])(const string&amp;); // array indexed by EventType<br>public:<br>    EventManager() {<br>        handlers[(int)EventType::BATTERY] = nullptr;<br>        handlers[(int)EventType::WIFI] = nullptr;<br>    }<br>    void registerHandler(EventType type, void (*handler)(const string&amp;)) {<br>        handlers[(int)type] = handler;<br>    }<br>    void fireEvent(EventType type, const string&amp; msg) {<br>        auto h = handlers[(int)type];<br>        if (h) h(msg);<br>        else cout &lt;&lt; &quot;[WARN] No handler for event\n&quot;;<br>    }<br>};<br>// --- Demo ---<br>int main() {<br>    EventManager manager;<br>    manager.registerHandler(EventType::BATTERY, onBattery);<br>    manager.registerHandler(EventType::WIFI, onWifi);<br>    manager.fireEvent(EventType::BATTERY, &quot;15% remaining&quot;);<br>    manager.fireEvent(EventType::WIFI, &quot;Office_WiFi&quot;);<br>    return 0;<br>     <br>}</pre><p>Instead of long chains of if-else, the event manager just <strong>jumps to the correct function pointer</strong>.</p><h3>2.2 Plugin Architecture</h3><p>The power of function pointers goes beyond “call me later.” They also let us design systems where new functionality can be plugged in at runtime, without changing the existing code.</p><p>That’s exactly how plugin systems work — at the core, a plugin is just “<em>a function that the host program can call dynamically</em>.”</p><p>Think about apps like Photoshop, VSCode, or game engines — they allow external modules (plugins) to extend functionality without changing the core codebase.</p><p><strong>The Problem (Without Plugins)</strong></p><p>Imagine you’re writing a math engine, You want to support operations like add, subtract, multiply, divide, At first, you might just hardcode:</p><pre>if (op == &quot;add&quot;)<br> return a + b;<br>else if (op == &quot;sub&quot;)<br> return a-b;<br>else if (op == &quot;mul&quot;)<br> return a*b; <br>else if (op == &quot;div&quot;)<br> return a / b;</pre><p>But every time you need a new operation (pow, mod, sqrt., .), you must go back into the engine’s source code and add another if That’s not scalable</p><p><strong>The Solution (Plugins with Function Pointers)</strong></p><p>Instead, we let plugins register their own functions with the engine All the engine cares about is a function pointer signature.</p><pre>#include &lt;iostream&gt;<br>#include &lt;unordered_map&gt;<br>#include &lt;string&gt;<br>#include &lt;cmath&gt;<br>typedef double (*MathOp)(double, double);<br>class OperationRegistry {<br>    std::unordered_map&lt;std::string, MathOp&gt; ops;<br>public:<br>    void registerOp(const std::string&amp; name, MathOp fn) {<br>        ops[name] = fn;<br>    }<br>    void execute(const std::string&amp; name, double a, double b) {<br>        if (ops.count(name)) {<br>            std::cout &lt;&lt; name &lt;&lt; &quot;(&quot; &lt;&lt; a &lt;&lt; &quot;, &quot; &lt;&lt; b &lt;&lt; &quot;) = &quot;&lt;&lt; ops[name](a, b) &lt;&lt; &quot;\n&quot;;<br>        } else {<br>            std::cout &lt;&lt; &quot;[ERROR] Operation &quot; &lt;&lt; name &lt;&lt; &quot; not found!\n&quot;;<br>        }<br>    }<br>};</pre><p><strong>Writing Plugins </strong><br>Each plugin is just a function that matches the signature:</p><pre>double add(double a, double b) {return a+b; }<br>double subtract(double a, double b) {return a-b;}<br>double power (double a, double b)  {return std::pow(a, b);}</pre><p><strong>Using the Plugin System</strong></p><pre>int main(){<br>   OperationRegistry registry;<br>   // Register plugins<br>   registry.registerOp(&quot;add&quot;,add);<br>   registry.registerOp(&quot;sub&quot;,sub);<br>   registry.registerOp(&quot;pow&quot;,power);<br>   // Use them dynamically<br>   registry.execute(&quot;add&quot; ,5, 3);<br>   registry.execute(&quot;pow&quot;, 2, 10);<br>   registry.execute(&quot;mul&quot;, 4, 2);<br>  return 0 ;<br>}</pre><p><strong>What’s Happening?</strong><br>• <em>registerop(“add” add);</em> -&gt; stores the address of add in the map. <br>• <em>registry.execute(“add”, 2,3);</em> -&gt; looks up the pointer and jumps directly to that function. • No branching, no switch, no recompiling core logic.</p><p>This is essentially a runtime dispatch table — the same mechanism compilers use internally for switch jump tables and virtual function tables.</p><h3>2.3 Async Programming</h3><p>We’ve seen function pointers as event callbacks (triggered by external signals) and as the foundation of plugin systems (dynamic function registration), Another important domain is asynchronous programming — you don’t want to block while waiting. Instead, you register a function pointer to be called later.</p><p><strong>The Core Idea </strong><br>When writing async code, you usually don’t want to block the main thread waiting for something to finish. Instead, you register a function (via a pointer) that the system will call after the operation completes.</p><p><strong>At runtime: </strong><br>1. The address of the function is stored in the pointer. <br>2. Work happens elsewhere (e.g. in another thread, 1/0 operation, or timer) <br>3. Once ready, the instruction pointer jumps to the function pointer’s address and executes it.</p><p>This is the mechanism behind callbacks in async APIs across operating systems, networking stacks, and GUI frameworks.</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;chrono&gt;<br><br>// Async Timer: takes a function pointer<br>void setTimeout(void (*cb)(), int delayMs) {<br>    std::thread([cb, delayMs]() {<br>        std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));<br>        cb(); // jump to the function stored in cb<br>    }).detach(); // detached thread, fire-and-forget<br>}<br><br>// Handlers (functions with matching signature)<br>void alarmHandler() {<br>    std::cout &lt;&lt; &quot;[ALERT] Timer expired\n&quot;;<br>}<br><br>void logHandler() {<br>    std::cout &lt;&lt; &quot;[LOG] Timer completed\n&quot;;<br>}<br><br>int main() {<br>    std::cout &lt;&lt; &quot;Starting timers...\n&quot;;<br><br>    setTimeout(alarmHandler, 2000);  // triggers alert after 2s<br>    setTimeout(logHandler, 3000);    // triggers log after 3s<br><br>    // Prevent main from exiting early<br>    std::this_thread::sleep_for(std::chrono::seconds(5));<br>    return 0;<br>}</pre><p><strong>Why Use Function Pointers Here?</strong></p><ul><li><strong><em>Dynamic Behavior</em></strong> : At runtime, different functions (alarmHandler, logHandler, or any future one) can be passed without modifying setTimeout.</li><li><strong><em>Decoupling</em></strong> : setTimeout doesn’t need to know what happens when time expires. It only needs a pointer to some function</li><li><strong><em>Control Flow</em></strong> : Instead of a switch inside setTimeout, the instruction pointer directly jumps to whichever function pointer was supplied</li><li><strong><em>Scalability</em></strong> : Multiple async tasks can run in parallel, each with its own cabllback.</li></ul><p>This is essentially a <strong>jump table</strong> — faster and cleaner than branching logic.</p><h3>3. Function Pointer Rules</h3><ol><li><strong>Same Signature Required:</strong><br> A function pointer can only point to functions that <strong>match the exact return type and parameter types</strong>.</li></ol><pre>double add(double a, double b) { return a + b; }<br>int (*fp)(int, int) = add; // ❌ Undefined behavior</pre><p><strong>Why:</strong> The CPU registers and calling conventions differ for int vs double. Calling through the wrong signature causes garbage values.</p><p><strong>2. Multiple Pointers Not Needed:</strong><br> One function pointer type can point to any function with the same signature.</p><pre>int x = 10;<br>int* p = &amp;x;<br>void (*fp)() = nullptr;<br>// p == fp; // ❌ compile error</pre><h3>4. Array of function pointer</h3><p>Array of function pointers is a data structure whose elements are pointer to a function. This allows to store multiple function address in one place and call them dynamically at runtime. We can define it using the syntax :</p><pre>returnType(*arrayname [size])(argTypes);</pre><p>Example:</p><pre>int add(int a, int b) {return a+b;}<br>int subs(int a, int b) {return a-b;}<br>int multiply(int a, int b) {return a*b;}<br><br>int main(){<br>  int (*operations[3]) (int,int) = {add,subs,multiply};<br>  int x=10, y=5;<br>  cout&lt;&lt;operations[1](x,y)&lt;&lt;endl;<br>  return 0;<br>}</pre><p>This replaces long if-else and switch case statements and is very useful in callback, plugin systems, interpreters.</p><h4>📝Note :</h4><p>Array of function pointers encodes both return type and parameter list so they don’t directly store different function signatures. But there are workaround:</p><ol><li><strong>use void*</strong></li></ol><pre>int add(int a, int b) {return a+b;}<br>int square (double X) {return X*X;}<br><br>void* funcs[2];<br>funcs[0] = (void*)add;<br>funcs[1] =(void*)square;<br><br>int(*f1) (int,int) = (int (*) (int,int)) funcs[0];<br>cout&lt;&lt;f1(2,3)&lt;&lt;endl;</pre><p>But this is very risky as compiler cannot check correctness.</p><p><strong>2. std::variant (C++ 17)</strong></p><p>This is a type-safe, modern way</p><pre>using FuncVariant = variant&lt;int(*)(int,int),double(*)(double)&gt;;<br><br>FuncVariant funcs[] = {add,square};<br>cout&lt;&lt; get&lt;int(*)(int,int)&gt; (funcs[0])(3,4) &lt;&lt;endl;</pre><p><strong>3. std::function</strong></p><p>It is very flexible and can mix different signature. But it has slight overhead verses has function pointers.</p><pre>vector&lt;function&lt;void()&gt;&gt; funcs;<br><br>funcs.push_back([] () {cout&lt;&lt;add(2,3) &lt;&lt;endl;});<br>funcs.push_back([](){cout&lt;&lt;square(4.2)&lt;&lt;endl;});<br><br>for(auto&amp; f:funcs) f();</pre><h3>5. Casting</h3><p>Normally, you don’t need casting in everyday code — compilers enforce type safety and signatures must match. But in <strong>system-level programming</strong> or <strong>interoperability scenarios</strong>, casting is sometimes unavoidable.</p><h4>5.1 When Casting Appears</h4><ul><li><strong>C library interop</strong> — Some C APIs accept generic void* function pointers, so you may cast back to a typed pointer.</li><li><strong>Generic callbacks</strong> — Frameworks often provide a single “catch-all” function pointer type.</li><li><strong>Jump tables</strong> — Low-level code sometimes stores raw addresses and casts them to function pointers.</li></ul><h4>5.2 Safe Casting in C++</h4><p>C++ provides explicit cast operators that make intent and safety clearer:</p><p><strong>static_cast</strong></p><ul><li>Use when converting between <strong>compatible types</strong> (e.g., base ↔ derived functions with same signature).</li><li>Safer than C-style cast since it fails at compile time if types are fundamentally incompatible.</li><li><strong>Note</strong>: In most function pointer use cases, static_cast is <strong>redundant and harmless</strong> — it’s often seen in legacy C-style code or codebases that want to make type intent explicit.</li></ul><pre>using Callback = void(*)(int);<br>void myFunc(int) {}<br><br>void wrapper(double) {}<br><br>int main() {<br>    Callback cb1 = myFunc; // OK<br>    // Callback cb2 = static_cast&lt;Callback&gt;(wrapper); // ❌ compile error (signature mismatch)<br>}</pre><p><strong>reinterpret_cast</strong></p><ul><li>The only way to forcefully convert between unrelated function pointer types.</li><li><strong>Dangerous</strong>: the call may compile but cause <strong>undefined behavior</strong> at runtime if signatures don’t match.</li></ul><pre>using F1 = int(*)(int, int);<br>using F2 = void(*)(double);<br><br>void printDouble(double x) { std::cout &lt;&lt; x &lt;&lt; &quot;\n&quot;; }<br><br>int main() {<br>    F1 f = reinterpret_cast&lt;F1&gt;(printDouble); <br>    // Compiles, but calling f(1,2) is undefined behavior ❌<br>}</pre><h4>Rule of Thumb</h4><p>Prefer <strong>no casting at all</strong> — design APIs with the right function pointer type.</p><p>If casting is necessary:</p><ul><li>✅ Use static_cast when types are <em>compatible</em>.</li><li>⚠️ Use reinterpret_cast only in <strong>low-level hacks</strong>, OS code, or when interfacing with C.</li></ul><p>For generic callbacks in modern C++, use std::function or std::any instead of unsafe casts.</p><h3>6. Static V/S Non-Static Member Function</h3><p>In C++, <strong>member functions</strong> can be <strong>static</strong> or <strong>non-static</strong>, and this affects how function pointers work.</p><h4>6.1 Non-static member function</h4><p>Consider this example:</p><pre>class A{<br>  void hello(std::string name){<br>      std::cout&lt;&lt;&quot;Hello : &quot;&lt;&lt;name&lt;&lt;std::endl;<br>    }<br>};<br><br>int  main(){<br>   A obj;<br>   obj.hello(&quot;abhilasha&quot;);<br>   return 0;<br>}</pre><p>The compiler translates it into</p><pre>hello(&amp;obj,&quot;abhilasha&quot;);</pre><p><strong>Key point:</strong> Every non-static member function secretly takes an extra argument: the this pointer, pointing to the object instance.</p><p>Effectively, the “real” type of hello is closer to:</p><pre>void hello(A* this, string name);</pre><h4>6.2 Pointer to Non-Static Member Function</h4><p>Because of the hidden this pointer, <strong>non-static member function pointers are not like normal function pointers</strong>:</p><pre>void (A::*mfp)(string) = &amp;A::hello; // ✅ Correct<br><br>// ❌ This won&#39;t compile<br>void (*fp)(string) = &amp;A::hello;     // Error: type mismatch</pre><p>You <strong>cannot call it directly</strong> like a free function. Instead, you need an object instance:</p><pre>A obj;<br>(obj.*mfp)(&quot;Abhilasha&quot;); // Calls hello on obj</pre><h4>6.3 Static Member Functions</h4><p>Static member functions <strong>do not have a </strong><strong>this pointer</strong>, so they behave like regular global functions in the namespace:</p><p>consider the following example :</p><pre>class B {<br>public:<br>    static void hi(string name) {<br>        cout &lt;&lt; &quot;Hi: &quot; &lt;&lt; name &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    void (*fp)(string) = &amp;B::hi; // ✅ Works like a normal function pointer<br>    fp(&quot;Abhilasha&quot;);<br>}</pre><p>Here, no this pointer sneaks in. The function is just a regular global function living in a namespace.</p><p>so,</p><pre>void(*fp)(std::string) = &amp;B::hi; //✅ works fine</pre><p>A pointer to a non-static member function is not just an address.</p><pre>class Base{virtual void f(); };<br>class Derived:Public Base{void f() override ;};</pre><p>Derived::f may live at a completely different address than Base::f. In multiple inheritance, the this pointer might need to be adjusted before calling the right function.</p><h4>6.4 Why Member Function Pointers Are Special</h4><ul><li>A pointer to a <strong>non-static member function</strong> is <strong>not just an address</strong>.</li><li>In inheritance, virtual functions may live at <strong>different addresses</strong> in derived classes.</li><li>In multiple inheritance, the this pointer may need <strong>adjustment</strong> before calling the correct function.</li><li>This is why sizeof(void(A::*)(string)) can be <strong>larger than a regular pointer</strong>.</li></ul><p>When you call through a member function pointer:</p><pre>(obj.*mfp)();</pre><p>The compiler:</p><ol><li>Loads the function pointer representation.</li><li>Adjusts the this pointer if needed.</li><li>Jumps to the correct code.</li></ol><p>This is also why C++ provides the <strong>.*</strong> and <strong>-&gt;*</strong> operators specifically for calling non-static member functions.</p><p>Function pointers in C++ are more than just a niche feature — they’re a powerful tool that allows your programs to be <strong>dynamic, modular, and efficient</strong>. They enable:</p><ul><li><strong>Callbacks</strong>: Decoupling events from actions, like in event handling or async programming.</li><li><strong>Plugin Systems</strong>: Adding new functionality at runtime without touching the core code.</li><li><strong>Jump Tables &amp; Dynamic Dispatch</strong>: Cleaner and faster alternatives to long chains of if-else or switch statements.</li></ul><p>However, with power comes responsibility: always respect <strong>function signatures</strong>, be careful with <strong>casting</strong>, and understand the difference between <strong>static and non-static member functions</strong>.</p><p>In modern C++, you also have safer alternatives like <strong>std::function</strong> or <strong>std::variant</strong> when dealing with mixed or dynamic function types.</p><p>Mastering function pointers gives you deeper insight into <strong>how C++ works under the hood</strong> and prepares you to write <strong>flexible, high-performance code</strong> — from embedded systems to large-scale applications.</p><p>So, the next time you see a callback, a plugin, or an async handler, remember: <strong>there’s probably a function pointer making it all work behind the scenes.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=471908aa4c0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointers in C++: Navigating Arrays, References, and Const Correctness]]></title>
            <link>https://medium.com/@k10abhilasha/pointers-in-c-navigating-arrays-references-and-const-correctness-441bb5c6b2c0?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/441bb5c6b2c0</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 12:30:21 GMT</pubDate>
            <atom:updated>2025-08-20T12:30:21.229Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In my last article, we explored the fundamentals of pointers in C++ — how to declare them, dereference them, how they exist in memory, using new and delete, and some common pitfalls to watch out for <a href="https://medium.com/@k10abhilasha/pointers-in-c-the-backbone-of-low-level-control-0d54b530c954">[Link]</a>. Pointers are powerful, but their true potential unfolds when we see how they interact with other C++ constructs. In this article, we’ll dive deeper into how pointers relate to arrays, the ins and outs of pointer arithmetic, references, and the nuances of const pointers versus pointers to const. By the end, you’ll have a more complete picture of how pointers can be used safely and effectively in real-world C++ code.</blockquote><h3>1. Pointer and Array</h3><p>In C++, when you assign an array to a pointer of the same type, the pointer points to the first element of the array. This allows you to traverse the array using pointer arithmetic.</p><pre>int arr[5] = {1,2,3,4,5};<br>int *ptr = arr;</pre><p>Here:</p><ul><li>arr is the name of the array, which decays to a pointer to its first element.</li><li>ptr now holds the memory address of arr[0].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*HGT3p4L_VyIMFLxRPdtNTA.png" /></figure><p>You can access elements via the pointer just like with the array:</p><pre>std::cout &lt;&lt; *ptr &lt;&lt; &quot;\n&quot;;     // prints 1<br>std::cout &lt;&lt; *(ptr + 2) &lt;&lt; &quot;\n&quot;; // prints 3</pre><h4>Pointer and Array with Different Types</h4><p>C++ is strict about pointer types. The type of a pointer must match the type of the array it points to, otherwise undefined behavior can occur.</p><p>Example: Wrong type pointer</p><pre>int arr[5] = {1, 2, 3, 4, 5};<br>char *cptr = (char*)arr; // forcefully casting int* to char*</pre><p>Here:</p><ul><li>arr is of type int[5].</li><li>cptr is a char* pointing to the same memory.</li></ul><p>This works in the sense that cptr points to the same memory, but the interpretation of data changes. Each int typically occupies 4 bytes (on most systems), while char is 1 byte. Accessing *cptr will only read the first byte of the first integer, not the whole number.</p><pre>std::cout &lt;&lt; *cptr &lt;&lt; &quot;\n&quot;; // prints garbage or truncated value</pre><blockquote>💡Important: Reading or writing through a pointer of a different type than the original object is type punning and can lead to undefined behavior, unless handled carefully (e.g., std::memcpy or std::bit_cast in C++20).</blockquote><h4>Using a void* pointer</h4><p>A void* can point to any type of data, including arrays:</p><pre>int arr[5] = {1, 2, 3, 4, 5};<br>void *vptr = arr; // okay, points to first element</pre><p>However:</p><ul><li>You cannot directly dereference a void* because the compiler doesn’t know the data type or size.</li><li>You must cast it back to the correct type before accessing:</li></ul><pre>int *iptr = static_cast&lt;int*&gt;(vptr);<br>std::cout &lt;&lt; iptr[2] &lt;&lt; &quot;\n&quot;; // prints 3</pre><blockquote>💡 Rule of thumb: Use void* only for generic memory handling or low-level APIs. For normal code, stick to typed pointers to avoid bugs.</blockquote><h4>Array Decay</h4><p>In C++, the name of an array <strong>decays</strong> into a pointer when used in most expressions, meaning it automatically converts to a pointer to the first element of the array.</p><p>A void* can point to any type of data, including arrays:<br>Internally, array name also translates into pointer which points to first address of block of memory assigned to the pointer. But it is a special type of pointer which can not be incremented or decremented i.e., it is a constant pointer.</p><pre>arr + 1 ;// this is okay points to first element of array<br>arr++ ;// this will throw an error</pre><p><strong>Array Decay in Functions</strong></p><p>When you pass an array to a function, it decays into a pointer. This means only the address of the first element is passed, not the entire array:</p><pre>void printFirstElement(int *ptr) {<br>    std::cout &lt;&lt; ptr[0] &lt;&lt; &quot;\n&quot;;<br>    std::cout&lt;&lt;sizeof(ptr)&lt;&lt; &quot;\n&quot;;<br>}<br><br>int main() {<br>    int arr[5] = {10, 20, 30, 40, 50};<br>    printFirstElement(arr); // arr decays to int*<br>}</pre><blockquote>Array decay is why functions cannot know the size of the array from a raw pointer. To preserve array size, you can pass a reference to the array or use <em>std::array</em>/<em>std::vector</em>.</blockquote><pre>int arr[5] = {1, 2, 3, 4, 5};<br><br>std::cout &lt;&lt; (arr == &amp;arr[0]) &lt;&lt; &quot;\n&quot;; // 1 (true)<br>std::cout &lt;&lt; (arr == &amp;arr)    &lt;&lt; &quot;\n&quot;; // 1 (true in value, but not in type)</pre><ul><li>arr → Decays into a pointer to the first element (int*).</li><li>&amp;arr[0] → Explicitly the address of the first element (int*).</li><li>&amp;arr → Address of the entire array object (int (*)[5] → pointer to array of 5 ints).</li></ul><p>So in memory, arr, &amp;arr[0], and &amp;arr often hold the same numeric address, but:</p><ul><li>Type of arr / &amp;arr[0]: int*</li><li>Type of &amp;arr: int (*)[5]</li></ul><pre>arr + 1;     // moves by sizeof(int)<br>&amp;arr + 1;    // moves by sizeof(int[5]) → jumps past the entire array</pre><blockquote>arr and &amp;arr[0] are effectively interchangeable.</blockquote><blockquote>&amp;arr is different—it’s a pointer to the whole array, which makes pointer arithmetic behave differently.</blockquote><h3>2. Pointer Arithmetic</h3><p>Pointer arithmetic in C++ is <strong>type-aware</strong>, meaning operations on a pointer move in steps that depend on the size of the type it points to. For example:</p><pre>int arr[3] = {10, 20, 30};<br>int *ptr = arr;<br><br>std::cout &lt;&lt; *(ptr) &lt;&lt; &quot;\n&quot;;     // prints 10<br>std::cout &lt;&lt; *(ptr + 1) &lt;&lt; &quot;\n&quot;; // prints 20</pre><blockquote>While doing pointer arithmetic , we need to be careful for the memory as we might accidently point to invalid memory location.</blockquote><p>Here, ptr + 1 doesn’t mean “add 1 byte”—it means “move to the next int.” Since an int is usually 4 bytes, the pointer moves forward by 4 bytes in memory.</p><p>Type of pointer pointer arithmetic:</p><h4>Increment /Decrement to pointer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*7WbUhYlBesJFkKeGqNbzBw.png" /><figcaption>incrementing/decrementing pointer</figcaption></figure><p>We can add or subtracts any constant number from a pointer. It shifts the pointer. It shifts the pointer the constant number of times the size of data type of pointer, i.e., when we do<strong><em> ptr + n ,</em></strong><em> </em>it translates into<em> </em><strong><em>ptr + n *(size of dataType)</em> </strong>and it moves the pointer n number of indexes.</p><pre>int arr = {1,2,3,4,5,6,7,8,9,10};<br>int *ptr = &amp;arr[4];<br>ptr = ptr + 2;<br>cour&lt;&lt;*ptr&lt;&lt;&quot;\n&quot;; //prints 7<br><br>ptr = ptr - 4;<br>cout&lt;&lt;*ptr&lt;&lt;&quot;\n&quot;; //prints 3<br></pre><ul><li>C++ allows a pointer to point <em>one past the last element</em> of an array.</li><li>You can compare it or subtract with valid pointers, but you cannot dereference it.</li></ul><pre>int arr[5] = {1,2,3,4,5};<br>int *end = arr + 5;  // legal, one past the last element<br>if (end == &amp;arr[5])  // ✅ allowed<br>    std::cout &lt;&lt; &quot;end is valid pointer, but not dereferenceable\n&quot;;<br>std::cout &lt;&lt; *end;   // ❌ Undefined behavior</pre><h4>Substruction of two pointer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*Z2u25Ntlk7_-mi1uYJJ9Bw.png" /></figure><p>When you subtract two pointers of the <strong>same type</strong>, the result is the number of elements between them (not raw bytes).</p><pre>int arr[] = {1,2,3,4,5,6,7,8,9,10};<br><br>int *ptr1 = &amp;arr[1];  // points to element 2<br>int *ptr2 = &amp;arr[5];  // points to element 6<br><br>int diff = ptr2 - ptr1; <br>cout &lt;&lt; diff &lt;&lt; &quot;\n&quot;; // prints 4</pre><p><strong>Why 4 and not 16?</strong></p><p>If the array starts at address 100:</p><ul><li>ptr1 = 104 (second element, assuming 4 bytes per int)</li><li>ptr2 = 120 (sixth element)</li></ul><p>Raw subtraction: 120 - 104 = 16.<br> But since these are int*, the compiler divides by sizeof(int) = 4.<br> So internally:</p><pre>(ptr2 - ptr1) = (120 - 104) / sizeof(int) = 16 / 4 = 4</pre><p><strong>⚠️ Pitfall: Undefined Behavior</strong></p><p>Pointer subtraction is only valid if both pointers point within the same array (or one past the end).</p><pre>int arr1[5], arr2[5];<br>int *p1 = &amp;arr1[0];<br>int *p2 = &amp;arr2[0];<br><br>int diff = p2 - p1;  // ❌ Undefined Behavior!</pre><p>Even if the addresses are numerically valid, the C++ standard does not define what happens — so relying on this is a bug.</p><ul><li>Subtracting pointers gives a result of type ptrdiff_t (signed).</li><li>This is important because it avoids overflow issues if ptr1 &lt; ptr2.</li></ul><pre>int arr[10];<br>int *p1 = &amp;arr[2];<br>int *p2 = &amp;arr[8];<br>auto diff = p1 - p2;  // type is ptrdiff_t, can be negative</pre><h4>Comparison to NULL</h4><ul><li>A pointer can be compared against NULL (or better, nullptr in modern C++) to check if it points to some valid memory.</li><li>NULL is traditionally defined as 0, while nullptr is a dedicated keyword of type std::nullptr_t.</li><li>Prefer nullptr because it avoids ambiguity in overload resolution.</li></ul><pre>int a = 20;<br>int *p = nullptr;  <br><br>std::cout &lt;&lt; (p == nullptr) &lt;&lt; std::endl; // prints 1 (true)  <br>p = &amp;a;  <br>std::cout &lt;&lt; (p == nullptr) &lt;&lt; std::endl; // prints 0 (false)</pre><h4>Comparison to another pointer</h4><p>When two pointers are compared, it’s their addresses that are compared, not the values they point to.</p><pre>int a = 20, b = 20;<br>int *p = &amp;a;<br>int *q = &amp;b;<br><br>std::cout &lt;&lt; (p == q) &lt;&lt; std::endl;   // 0 → different addresses  <br>std::cout &lt;&lt; (*p == *q) &lt;&lt; std::endl; // 1 → values are equal</pre><p><strong>Relational comparisons (</strong><strong>&lt;, </strong><strong>&gt;)</strong></p><ul><li>Only defined if both pointers refer into the same array (or one past the end).</li><li>Otherwise → Undefined Behavior (even if numerically the addresses look comparable).</li></ul><pre>int arr[5];<br>int *p = &amp;arr[1];<br>int *q = &amp;arr[4];<br>std::cout &lt;&lt; (p &lt; q) &lt;&lt; std::endl;  // ✅ defined  <br><br>int x, y;<br>int *p1 = &amp;x;<br>int *p2 = &amp;y;<br>std::cout &lt;&lt; (p1 &lt; p2);  // ❌ UB (different objects)</pre><p><strong>Equality (</strong><strong>==, </strong><strong>!=)</strong></p><ul><li>Well-defined for any pointers of the same type (even if unrelated).</li><li>They’re equal only if they point to the same object (or both null).</li></ul><p><strong>Comparing function pointers vs object pointers</strong></p><ul><li>Function pointer comparisons are defined but not interchangeable with object pointers.</li></ul><pre>#include &lt;iostream&gt;<br><br>void foo() { std::cout &lt;&lt; &quot;foo\n&quot;; }<br>void bar() { std::cout &lt;&lt; &quot;bar\n&quot;; }<br><br>int main() {<br>    // --- Object pointers ---<br>    int a = 10, b = 20;<br>    int* p1 = &amp;a;<br>    int* p2 = &amp;b;<br><br>    std::cout &lt;&lt; &quot;Object pointer equality: &quot; &lt;&lt; (p1 == p2) &lt;&lt; &quot;\n&quot;; // 0 (false)<br><br>    // --- Function pointers ---<br>    void (*f1)() = &amp;foo;<br>    void (*f2)() = &amp;bar;<br>    void (*f3)() = &amp;foo;<br><br>    std::cout &lt;&lt; &quot;f1 == f2 : &quot; &lt;&lt; (f1 == f2) &lt;&lt; &quot;\n&quot;; // 0 (different funcs)<br>    std::cout &lt;&lt; &quot;f1 == f3 : &quot; &lt;&lt; (f1 == f3) &lt;&lt; &quot;\n&quot;; // 1 (same func)<br><br>    // --- Invalid mixing ---<br>    // int* objPtr = &amp;a;<br>    // void (*funcPtr)() = &amp;foo;<br>    // if (objPtr == funcPtr) {} // ❌ Compilation error: types are unrelated<br><br>    return 0;<br>}</pre><p>In C++:</p><ul><li>An object pointer (like int*, char*, MyClass*) points to a memory location in data space (stack, heap, or static storage).</li><li>A function pointer (like void(*)()) points to a memory location in code space (the machine instructions of the function).</li></ul><p>These two belong to different “domains”:</p><ul><li>The type system enforces that you can’t compare them, because their representations and semantics are unrelated.</li><li>Even though <em>both are just addresses under the hood</em>, the standard says object pointers and function pointers are not interchangeable types.</li></ul><h3>3. Pointers and Reference</h3><p>A reference is an alias (another name) for already existing variable.</p><pre>int a = 10;<br>int&amp; ref = a;   // ref is another name for a</pre><h4>Key properties :</h4><ul><li>Must be initialized at declaration.</li><li>Cannot be reseated (once bound, always refers to the same object).</li><li>Cannot be nullptr (unlike pointers).</li><li>No multi-level references (int&amp;&amp;&amp; not allowed, but pointers like int*** are valid).</li><li>Takes no extra conceptual space (though compilers usually implement them as hidden pointers).</li></ul><h4>🔹 Behind the scenes</h4><ul><li>References are often implemented as constant pointers by the compiler:</li></ul><pre>int a = 5;<br>int&amp; ref = a; <br>// internally similar to: int* const ref = &amp;a;</pre><ul><li>They don’t occupy extra storage in your code, but at assembly level you may see them passed like pointers.</li></ul><h4>🔹 Special cases</h4><ol><li><strong>Const references and temporaries</strong></li></ol><p>A const&amp; can bind to a temporary value:</p><pre>const int&amp; r = 5;   // valid: compiler extends lifetime of temporary</pre><p><strong>2. Rvalue references (</strong><strong>&amp;&amp;) – C++11 onwards</strong></p><ul><li>Used in <strong>move semantics</strong> and <strong>perfect forwarding</strong>.</li><li>Allow binding to temporaries:</li></ul><pre>int&amp;&amp; r = 10;     // binds to temporary</pre><h4>Why do we need references?</h4><ol><li>Function parameters<br> Pass by reference avoids expensive copies.</li></ol><pre>void update(int&amp; x) { x = 100; }</pre><p>2. Return values<br> Enable chaining and direct access.</p><pre>int&amp; get() { return value; }</pre><p>3. Operator overloading<br> Needed for returning references in assignment operators, etc.</p><h3>4. Const pointer versus pointer to const</h3><h4>Pointer to const</h4><p>A pointer to const is a pointer who is pointing to a constant variable.</p><pre>int a = 20;<br>const int *p = &amp;a; // pointer to const</pre><p>It essentially marks the variable as constant and does not allow the value to change. But we can change the variable it is pointing to</p><pre>int a = 20, b= 30;<br>const int *p = &amp;a;<br>a = 40; // allowed <br>p = &amp;b // allowed<br>*p = 50; // ❌ not allowed</pre><pre>   +-----+       +----+<br>p→ |  a  | 10    |  b | 20<br>   +-----+       +----+<br>     ^<br>     | (can reassign p to point to b)</pre><h4>Const pointer</h4><p>A const pointer is a pointer which can not change the variable it is pointing to .</p><pre>int a = 20, b = 30;<br>int *const ptr = &amp;a;<br>*ptr = 50; // allowed<br>ptr = &amp;b // ❌ not allowed</pre><p>even reassigning to same variable will throw error.</p><pre>int a = 20, b = 30;<br>int *const ptr = &amp;a;<br>*ptr = 50; // allowed<br>ptr = &amp;a; // ❌ not allowed</pre><pre>   +-----+ <br>p→ |  a  | 10<br>   +-----+<br> (p is fixed to &amp;a)</pre><h4>Const pointer to const</h4><p>A const pointer to const is a const pointer to a constant , where neither the pointer can point to any other variable nor it can change the value it is pointing to.</p><pre>int a = 10, b = 20;<br>const int* const p = &amp;a;   // const pointer to const int<br>*ptr = 50; // ❌ not allowed<br>ptr = &amp;a; // ❌ not allowed</pre><pre>   +-----+ <br>p→ |  a  | 10<br>   +-----+<br> (p is fixed to &amp;a and read-only)</pre><p><strong>const applies to what’s on its left (or to its right if nothing is on the left).</strong></p><pre>const int *p;   // pointer to const int<br>int const *p;   // same as above<br>int * const p;  // const pointer to int</pre><p><strong>const correctness in function parameters</strong></p><pre>void f(const int* p);    // function guarantees not to modify *p<br>void g(int* const p);    // function guarantees p won&#39;t change (rarely used)</pre><p>Most APIs use const int* for read-only inputs.<br> Very few use int* const (because pointer immutability at call site is rarely useful).</p><p><strong>const with </strong><strong>void* is special</strong></p><pre>const void* p;  // pointer to const unknown type (cannot deref safely)<br>void* const p;  // const pointer to void</pre><p><strong>const pointers in </strong><strong>const objects</strong></p><pre>class A {<br>    int x;<br>public:<br>    void set(int val) { x = val; }      // normal<br>    int get() const { return x; }       // &#39;this&#39; is of type &#39;const A* const&#39;<br>};<br></pre><p>Behind the scenes</p><ul><li>For set(int val) Signature is like:</li></ul><pre>void set(A* const this, int val);</pre><blockquote>👉 this is a <strong>const pointer</strong> to a non-const object (pointer itself fixed, but you can mutate object).</blockquote><ul><li>For int get() const Signature is like:</li></ul><pre>int get(const A* const this);</pre><blockquote>👉 Now this is a <strong>const pointer to const object</strong>:</blockquote><blockquote>Pointer itself cannot change (always points to the same object).</blockquote><blockquote>Object contents cannot change.</blockquote><pre>int get() const {<br>    x = 42;  // ❌ error: cannot modify member in const method<br>    return x;<br>}</pre><p>But calling non-const methods from a const object also fails:</p><pre>const A obj;<br>obj.set(10); // ❌ not allowed<br>obj.get();   // ✅ allowed</pre><p><strong>constexpr</strong> vs <strong>const</strong></p><p>Both restrict mutability, but in <strong>different stages</strong>:</p><p>const</p><ul><li>Value is read-only after initialization.</li><li>Decided at runtime (not necessarily compile time).</li></ul><p>Example:</p><pre>const int x = time(0);  // ✅ allowed<br>// value fixed after initialization, but not known at compile time</pre><p>constexpr</p><ul><li>Value must be a <strong>compile-time constant</strong>.</li><li>Useful for array sizes, template parameters, switch cases.</li></ul><p>Example:</p><pre>constexpr int y = 10;        // ✅ known at compile time<br>constexpr int z = time(0);   // ❌ error, not compile-time constant</pre><p>Mastering pointers and their arithmetic is not just about writing correct C++ , it&#39;s about writing safe and secure code. Misstep with pointers often lead to undefined behavior, which can manifest as crashes , memory corruption, or even serious security vulnerabilities. Understanding how pointers work , where they reside , and how arithmetic affects them is fundamental for every c++ developer who wants to wield the full power of language responsibity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=441bb5c6b2c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointers in C++ : The Backbone of Low-Level control]]></title>
            <link>https://medium.com/@k10abhilasha/pointers-in-c-the-backbone-of-low-level-control-0d54b530c954?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d54b530c954</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pointers]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 18:46:41 GMT</pubDate>
            <atom:updated>2025-08-21T10:56:39.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pointers in C++ : The Backbone of Low-Level control</h3><h3>Pointers basics</h3><p>Pointers are one of the most powerful features of C++. They allow direct control over memory at a low level, making them a staple in gaming engines, operating systems, and chipset-level programming. This fine-grained control is one of the key reasons why C++ is considered fast and efficient.</p><h3>1. What is a pointer ?</h3><p>A Pointer is a variable which stores <em>memory address</em> of another variable.</p><p>We can think of it like</p><ul><li>A variable is a house that holds the value</li><li>A pointer is the GPS location of the house</li></ul><pre>int a= 20;<br>int *ptr = &amp;a;</pre><p>Here :</p><ul><li>a is an integer variable storing the value 20</li><li>ptr is a pointer to integer storing the memory address of a</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*OmYbbktIOY1JMrqDCS6PUA.jpeg" /><figcaption>a and ptr</figcaption></figure><p>Pointers can be created using the syntax :</p><pre>dataType *variable_name ;</pre><ul><li>dataType can be any datatype int, char, double . It shows the type of value pointer is pointing to.</li><li>* denotes that it is a pointer</li></ul><pre>char *charPtr; <br>int *intPtr; <br>double *doubleptr; <br>int **pointerToPointer ;</pre><blockquote>💡<em>Note:</em></blockquote><blockquote><em>Both</em><strong> </strong>int* ptr;<em> and </em>int *ptr;<em> are valid - but keep one style consistent across your codebase.</em></blockquote><h3>2. Dereferencing a pointer</h3><p>Dereferencing means accessing the value stored at the memory address a pointer holds We use the * operator for this .</p><p>Think of it like following the GPS coordinates (pointer) to reach the house and open the door to see the value inside</p><pre><br>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    int a = 20;<br>    int *ptr = &amp;a;<br>    cout&lt;&lt;ptr&lt;&lt;endl;//  prints memory address of a<br>    cout &lt;&lt;*ptr&lt;&lt;endl; // prints the value of a<br><br>    return 0;<br>}</pre><p>The output will be something like , exact address will change in each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*ucUoWqL8ZUprff4JXEsc9Q.jpeg" /><figcaption>Printing value stored in variable using pointer dereferencing</figcaption></figure><h3>3. Pointers in memory</h3><p>Pointers themselves are just variables, so they live in the stack by default.<br> However, the memory they point to can be in the stack or the heap depending on allocation.</p><h4>Example 1 — Heap Allocation</h4><pre>class sample{<br>public: <br>    int a,b;<br>    sample(int a =0 , int b=0){<br>        this-&gt;a = a;<br>        this-&gt;b = b;<br>        cout&lt;&lt;&quot;Sample Created&quot;&lt;&lt;endl;<br>    }  <br>};<br>int main(){<br>  sample *obj = new sample();<br>  delete obj;<br>}</pre><p>Here:</p><ul><li>obj is stored in stack.</li><li>Sample object (a and b) is stored in heap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*QZnDTzvmRIhKaj3t8RPB4g.png" /></figure><h4>Example 2 — Stack Allocation</h4><pre>int a = 20;<br>int *ptr = &amp;a </pre><ul><li>Both ptr and a live in stack memory.</li><li>Since it’s stack-allocated, you don’t need to manually free memory.</li></ul><h4>Heap-Allocated Pointer Variables</h4><pre>int** pp = new int*;<br>*pp = new int(30);</pre><p>Now both the pointer (pp) and the integer it points to are in the heap.</p><h3>4. new and delete V/S malloc and free</h3><p><strong>How Does </strong><strong>free() Know How Much Memory to Release?</strong></p><p><em>When you allocate memory:</em></p><pre>int* p = (int*)malloc(40);<br>free(p);</pre><p>free doesn’t magically remember you asked for 40 bytes — the memory allocator stores metadata just before your allocated block in memory.<br> This metadata includes the allocation size, so free can release the correct amount.</p><blockquote>💡 With delete[], the compiler may store extra information to call destructors for all elements.</blockquote><p><strong>Can We Mix </strong><strong>free() and </strong><strong>delete()?</strong></p><p>No, you should never mix them.</p><ul><li>Memory allocated with new must be freed with delete (or delete[] for arrays).</li><li>Memory allocated with malloc() must be freed with free().</li></ul><p><strong>Why ?</strong></p><ol><li>new not only allocates memory but also calls the constructor.</li><li>delete not only frees memory but also calls the destructor before releasing it.</li><li>malloc()/free() only allocate and release raw memory — they don’t run constructors or destructors.</li></ol><p><strong>What happens if we mix them ?</strong></p><ul><li>Using free() on memory from new skips the destructor — leading to resource leaks.</li><li>Using delete on memory from malloc() makes the compiler try to run a destructor on a raw block — undefined behavior.</li></ul><p><strong>Example bad❌</strong></p><pre>MyClass* obj = new MyClass();<br>free(obj); // ❌ Destructor won&#39;t be called — undefined behavior</pre><p><strong>Correct usage ✅</strong></p><pre>// Using new/delete<br>MyClass* obj = new MyClass();<br>delete obj; <br><br>// Using malloc/free<br>MyClass* raw = (MyClass*)malloc(sizeof(MyClass));<br>free(raw);</pre><h3><strong>5. Pitfalls &amp; Safety</strong></h3><h4>Dangling pointers</h4><p>A dangling pointer is a pointer that points to a memory location which is no longer valid — usually because the memory has been freed or the variable has gone out of scope.</p><p>Think of it like having the GPS coordinates of a house that has been demolished — you <em>can</em> try to go there, but you’ll end up in undefined territory (literally undefined behavior in C++).</p><p><strong>Example -1</strong></p><pre>int* fun() {<br>    int a = 20;   // local variable on stack<br>    return &amp;a;    // returning address of a stack variable<br>}<br><br>int main() {<br>    int* p = fun();  <br>    // &#39;a&#39; is destroyed after fun() ends, p now dangles<br>    cout &lt;&lt; *p; // undefined behavior — could crash or print garbage<br>}</pre><p><strong>Example -2</strong></p><pre>int* p = new int(42);<br>delete p;   // memory freed<br><br>cout &lt;&lt; *p; // p now dangles — accessing freed memory is undefined behavior</pre><p>After calling delete, p is left dangling.<br> Good practice is to set it to nullptr immediately after deletion:</p><pre>delete p;<br>p = nullptr;</pre><h4>Wild pointers</h4><p>A wild pointer is a pointer that points to some random memory location, without being initialized to a known value (like nullptr).</p><p>Think of it like having random GPS coordinates — there might be a house there, or there might be a swamp full of crocodiles. Either way, going there without knowing is risky.</p><pre>int* p;   // uninitialized — contains garbage address<br>*p = 42;  // ❌ undefined behavior — could crash or corrupt memory</pre><p>Here, p could be pointing anywhere. Writing to such memory can overwrite critical parts of your program, leading to unpredictable behavior.</p><ul><li><strong><em>Silent corruption: </em></strong>They can overwrite heap metadata, stack frames, or vtables without immediate crash, leading to security vulnerabilities (buffer overflows, code injection).</li><li><strong><em>Non-deterministic behavior:</em></strong> The bug may only appear under certain memory layouts, making it extremely hard to debug.</li><li><strong><em>Security impact:</em></strong> This is a common source of exploitable vulnerabilities in C/C++.</li></ul><p>Causes of Wild Pointers:</p><ul><li><strong><em>Dangling → wild: </em></strong>After free/delete, if the pointer is reused without reset, it becomes wild.</li><li><strong><em>Out-of-scope references: </em></strong>Returning addresses of stack variables that no longer exist.</li><li><strong><em>Pointer arithmetic gone wrong:</em></strong> Incrementing past array bounds.</li><li><strong><em>Type punning gone bad:</em></strong> Casting to unrelated pointer types without ensuring valid memory.</li></ul><p><strong>Example — 1</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>struct A {<br>    int x;<br>    double y;<br>};<br><br>struct B {<br>    char c;<br>    int z;<br>};<br><br>int main() {<br>    A a{42, 3.14};<br>    B* b = (B*)&amp;a; // reinterpret_cast in disguise (C-style cast)<br><br>    cout &lt;&lt; b-&gt;z &lt;&lt; endl; // ❌ undefined behavior<br>    b-&gt;c = &#39;X&#39;;           // may overwrite parts of double y<br><br>    return 0;<br>}</pre><p><strong>Example — 2</strong></p><pre>int num = 0x12345678;<br>char* p = (char*)&amp;num;<br>*p = 0xFF;  // modifies only the first byte, rest of int is garbage now</pre><p>How to avoid wild pointers :</p><ol><li>Always initialize pointers when declaring them:</li></ol><pre>int* p = nullptr;  // safe, points to nothing</pre><p>2. Assign pointers a valid address before use:</p><pre>int a = 10;<br>int* p = &amp;a; // now safe to use</pre><p>3. After freeing memory, set the pointer to nullptr:</p><pre>delete p;<br>p = nullptr; // no longer wild</pre><p>4. Avoid unsafe casts — Prefer using std::bit_cast (C++20) for reinterpretation:</p><pre>#include &lt;bit&gt;<br>#include &lt;cstring&gt;<br><br>float f = 3.14f;<br>uint32_t bits = std::bit_cast&lt;uint32_t&gt;(f); // safe reinterpretation</pre><p>5. Use unions for controlled type punning (C++20 std::variant is safer):</p><pre>union Data {<br>    int i;<br>    float f;<br>};<br>Data d;<br>d.i = 42;</pre><p>How to check for wild pointer:</p><ul><li>Use tools: AddressSanitizer (ASan), Valgrind, UBSan to catch wild accesses early.</li><li>Enable compiler warnings: -Wall -Wextra -Wuninitialized -Werror.</li></ul><h4><strong>Memory Leak</strong></h4><p>A memory leak occurs when heap memory is allocated but never released. Over time, unreleased memory accumulates, causing the heap to grow until the system slows down or crashes due to memory exhaustion.</p><pre>int* p = new int(42);<br>// forgot to delete p;<br>// memory stays allocated until program ends</pre><p>Think of the heap as a giant hotel. When you new or malloc, you “check into” a room. When you delete or free, you “check out.”</p><p>If you forget to check out, that room stays locked forever — even though no one’s inside. Do this enough times, and one day, new guests arrive (new allocations)… and the hotel says: “Sorry, no vacancy.” That’s when your program crashes.</p><p><strong>When it happens :</strong></p><ol><li>Early exit or exception before cleanup:</li></ol><pre>#include &lt;iostream&gt;<br><br>void processData(bool failEarly) {<br>    int* data = new int[100]; // allocated but not freed<br>    if (failEarly) {<br>        std::cout &lt;&lt; &quot;Exiting early...\n&quot;;<br>        return; // 🚨 Leak here — &#39;delete[] data&#39; never called<br>    }<br>    delete[] data; // cleanup if we reach here<br>}<br><br>int main() {<br>    processData(true); // triggers leak<br>}</pre><p>2. Static or global objects that allocate and never release.</p><pre>#include &lt;string&gt;<br><br>struct Logger {<br>    Logger() { buffer = new char[1024]; }<br>    ~Logger() { delete[] buffer; }<br>    char* buffer;<br>};<br><br>// Global object — lifetime = program lifetime<br>static Logger* globalLogger = new Logger(); // never deleted — leaks until process exit<br><br>int main() {<br>    // globalLogger used here...<br>}</pre><p>3. Multi-threaded logic where one thread skips cleanup.</p><pre>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>void worker(bool cleanup) {<br>    int* data = new int[50];<br>    if (!cleanup) return; // 🚨 Memory never freed for this thread<br>    delete[] data;<br>}<br><br>int main() {<br>    std::thread t1(worker, true);<br>    std::thread t2(worker, false); // leak here<br>    t1.join();<br>    t2.join();<br>}</pre><p>4. Smart pointer cycles — std::shared_ptr pointing to each other so ref-count never hits zero.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>struct Node {<br>    std::shared_ptr&lt;Node&gt; next;<br>    ~Node() { std::cout &lt;&lt; &quot;Node destroyed\n&quot;; }<br>};<br><br>int main() {<br>    auto n1 = std::make_shared&lt;Node&gt;();<br>    auto n2 = std::make_shared&lt;Node&gt;();<br><br>    // Circular reference — ref count never reaches 0<br>    n1-&gt;next = n2;<br>    n2-&gt;next = n1;<br><br>    // Both leaked — destructors never called<br>}</pre><p><strong>How to Catch the Culprits 🔍</strong></p><ul><li>Valgrind (Linux) — shows where each leak came from.</li><li>AddressSanitizer (-fsanitize=address) — great for development builds.</li><li>Windows CRT Debug Heap (_CrtDumpMemoryLeaks() for Windows folks).</li></ul><p><strong>Fixing Memory Leaks 🛠</strong></p><p>1. Early Exit or Exception Before Cleanup</p><p>Problem: Memory allocated before an early return is never freed.<br>Fix: Use RAII (Resource Acquisition Is Initialization) — e.g., std::vector or std::unique_ptr.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br><br>void processData(bool failEarly) {<br>    std::vector&lt;int&gt; data(100); // allocated on heap internally, freed automatically<br>    if (failEarly) {<br>        std::cout &lt;&lt; &quot;Exiting early...\n&quot;;<br>        return; // No leak — vector cleans up<br>    }<br>}<br><br>int main() {<br>    processData(true);<br>}</pre><p>2. Static or Global Objects That Never Release</p><p><strong>Problem:</strong> Dynamically allocated globals persist until program exit.<br><strong>Fix: </strong>Use a stack-based global (automatic cleanup) or a smart pointer with controlled lifetime.</p><pre>#include &lt;string&gt;<br><br>struct Logger {<br>    Logger() { buffer = new char[1024]; }<br>    ~Logger() { delete[] buffer; }<br>    char* buffer;<br>};<br><br>// Automatic lifetime — destroyed at program exit without leaks<br>Logger globalLogger; <br><br>int main() {<br>    // globalLogger used here...<br>}</pre><p>3. Multi-Threaded Logic Skipping Cleanup</p><p><strong>Problem: </strong>Some threads exit without freeing their memory.<br><strong>Fix: </strong>Use smart pointers or containers that manage cleanup automatically.</p><pre>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br>#include &lt;memory&gt;<br><br>void worker(bool cleanup) {<br>    auto data = std::make_unique&lt;int[]&gt;(50); // auto-freed<br>    if (!cleanup) return; // Still no leak<br>}<br><br>int main() {<br>    std::thread t1(worker, true);<br>    std::thread t2(worker, false);<br>    t1.join();<br>    t2.join();<br>}</pre><p>4. Smart Pointer Cycles (Shared Pointer Trap)</p><p><strong>Problem: </strong>Circular references keep reference counts &gt; 0 forever.<br><strong>Fix:</strong> Break the cycle with std::weak_ptr.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>struct Node {<br>    std::weak_ptr&lt;Node&gt; next; // weak pointer breaks cycle<br>    ~Node() { std::cout &lt;&lt; &quot;Node destroyed\n&quot;; }<br>};<br><br>int main() {<br>    auto n1 = std::make_shared&lt;Node&gt;();<br>    auto n2 = std::make_shared&lt;Node&gt;();<br><br>    n1-&gt;next = n2;<br>    n2-&gt;next = n1;<br><br>    // Both destroyed automatically — no leaks<br>}</pre><blockquote>💡 <strong>Rule of thumb</strong>: Always think — “If I check in, who’s checking me out?”<br> If you don’t know the answer, you’re one bug away from a memory leak.</blockquote><h4>Double delete</h4><p>A double delete happens when you call delete (or delete[]) on the same pointer more than once without resetting it to nullptr.</p><p>It’s like selling your house, handing over the keys… and then showing up a week later to “sell” it again — only now, someone else might be living there. The second “sale” (delete) will end badly.</p><pre>int main() {<br>    int* p = new int(42);<br>    delete p;   // ✅ first delete — fine<br><br>    delete p;   // ❌ second delete — undefined behavior<br>    return 0;<br>}</pre><p>Why is it dangerous :</p><ul><li>Undefined behavior — program may crash immediately, or silently corrupt memory.</li><li>Heap metadata corruption — allocators track freed blocks, so freeing twice can break their bookkeeping, leading to random crashes later.</li></ul><p>When it happens :</p><ul><li>Shared cleanup logic: two functions both think they “own” the pointer and try to delete it.</li></ul><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void cleanup(int* p) {<br>    delete p;  // ❌ deletes pointer<br>}<br><br>void process(int* p) {<br>    cleanup(p);<br>    cleanup(p); // ❌ double delete - UB<br>}<br><br>int main() {<br>    int* ptr = new int(42);<br>    process(ptr);<br>}</pre><blockquote>💡 <strong>Fix:</strong> Use std::unique_ptr so ownership is clear.</blockquote><pre>#include &lt;memory&gt;<br>void cleanup(unique_ptr&lt;int&gt; p) { /* auto cleanup */ }</pre><ul><li>Complex error handling: pointer freed in both success and error paths.</li></ul><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    int* p = new int(42);<br><br>    if (/* some condition */ false) {<br>        delete p; // ❌ freed here<br>        return 1;<br>    }<br><br>    // later...<br>    delete p; // ❌ freed again if condition was true<br>}</pre><blockquote>💡 <strong>Fix:</strong> Wrap in RAII object (unique_ptr) so cleanup is done once automatically.</blockquote><ul><li>Exception handling: pointer deleted in catch and also in normal destructor.</li></ul><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Resource {<br>    int* data;<br>public:<br>    Resource() { data = new int(42); }<br>    ~Resource() { delete data; } // cleanup here<br>    void riskyOperation() {<br>        try {<br>            throw runtime_error(&quot;Something went wrong&quot;);<br>        } catch (...) {<br>            delete data; // ❌ cleanup again - double delete<br>            throw;<br>        }<br>    }<br>};<br><br>int main() {<br>    try {<br>        Resource r;<br>        r.riskyOperation();<br>    } catch (...) {}<br>}</pre><blockquote>💡 <strong>Fix:</strong> Remove manual delete from catch and let the destructor handle cleanup.</blockquote><h4>Race Conditions with Pointer</h4><p>Pointers become dangerous in multi-threaded code when two or more threads read or write through the same pointer without proper synchronization.<br> This can lead to data races, undefined behavior, or corrupted memory.</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>int* sharedPtr;<br><br>void writer() {<br>    for (int i = 0; i &lt; 1000; i++) {<br>        *sharedPtr += 1; // writing without lock<br>    }<br>}<br><br>void reader() {<br>    for (int i = 0; i &lt; 1000; i++) {<br>        std::cout &lt;&lt; *sharedPtr &lt;&lt; &quot;\n&quot;; // reading without lock<br>    }<br>}<br><br>int main() {<br>    int value = 0;<br>    sharedPtr = &amp;value;<br><br>    std::thread t1(writer);<br>    std::thread t2(reader);<br><br>    t1.join();<br>    t2.join();<br>}</pre><p>💡 <strong>Problem:</strong> The compiler assumes no concurrent modification → reads/writes interleave unpredictably, causing garbage output or crashes.</p><p><strong>Fix</strong> with Mutex</p><pre>#include &lt;mutex&gt;<br>std::mutex mtx;<br><br>void safeWriter() {<br>    for (int i = 0; i &lt; 1000; i++) {<br>        std::lock_guard&lt;std::mutex&gt; lock(mtx);<br>        *sharedPtr += 1;<br>    }<br>}</pre><p><strong>Atomic Pointers</strong></p><p>If multiple threads need to update the pointer itself (not the data it points to), use std::atomic&lt;T*&gt;.</p><pre>#include &lt;atomic&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>struct Data { int value; };<br>std::atomic&lt;Data*&gt; atomicPtr{nullptr};<br><br>void writer() {<br>    for (int i = 0; i &lt; 100; i++) {<br>        atomicPtr.store(new Data{i});<br>    }<br>}<br><br>void reader() {<br>    for (int i = 0; i &lt; 100; i++) {<br>        Data* ptr = atomicPtr.load();<br>        if (ptr) std::cout &lt;&lt; ptr-&gt;value &lt;&lt; &quot;\n&quot;;<br>    }<br>}</pre><blockquote>💡 Important: Atomicity here applies only to the pointer variable, not the object’s internal state — for that, you still need locks.</blockquote><h3>6. Void Pointers</h3><p>A void* (void pointer) is a special kind of pointer that can hold the address of any data type — but here’s the catch:</p><ul><li>It does not have a type, so the compiler has no idea what it’s pointing to.</li><li>Because the compiler doesn’t know the type, it doesn’t know the size of the object either.</li><li>And if you don’t know the size, you can’t perform pointer arithmetic or dereference it safely without converting it first.</li></ul><h4>Why void pointers can’t be directly dereferenced</h4><p>Think of a pointer like a GPS coordinate <em>plus</em> a blueprint of the house there.<br> If the blueprint says “it’s a 2-story house, each floor has 10 rooms,” you know exactly how to walk inside and reach room #3.</p><p>A void* is like a GPS coordinate <strong>without</strong> the blueprint — you can go to the address, but you don’t know if it’s a house, an apartment, or a McDonald’s.<br> So the compiler refuses to dereference it — because it doesn’t know how big a “unit” is.</p><h4>Declaring and assigning void pointers</h4><pre>int a = 42;<br>double b = 3.14;<br><br>void* ptr;   // can point to anything<br>ptr = &amp;a;    // points to an int<br>ptr = &amp;b;    // now points to a double</pre><blockquote>💡 The same ptr variable can hold addresses of <strong>different types</strong> during its lifetime.</blockquote><h4>Dereferencing — Needs explicit casting</h4><p>You must cast a void* to the correct type before dereferencing, otherwise you’ll get undefined behavior.</p><pre>int x = 10;<br>void* ptr = &amp;x;<br><br>// ❌ std::cout &lt;&lt; *ptr; // Compiler error<br>std::cout &lt;&lt; *(static_cast&lt;int*&gt;(ptr)) &lt;&lt; &quot;\n&quot;; // ✅ 10</pre><h4>Pointer conversions with void pointers</h4><ul><li>Any pointer type can be implicitly converted to void* — no cast required.</li><li>Converting from void* back to a typed pointer requires an explicit cast (C-style or static_cast).</li></ul><pre>char c = &#39;A&#39;;<br>char* cp = &amp;c;<br><br>void* vp = cp;  // ✅ implicit<br>char* cp2 = static_cast&lt;char*&gt;(vp); // ✅ explicit back to char*</pre><h4>Pointer arithmetic limitation</h4><p>Since void* has no size information, pointer arithmetic is not allowed in C++ (unlike C where void* arithmetic is compiler-dependent).</p><pre>void* vp = &amp;a;<br>// vp++; // ❌ Error: size of void is unknown</pre><p>If you need arithmetic, cast to a char* (size = 1 byte) or to the correct type:</p><pre>int arr[3] = {10, 20, 30};<br>void* vp = arr;<br><br>int* ip = static_cast&lt;int*&gt;(vp);<br>ip++; // now points to arr[1]</pre><h4>Risks &amp; pitfalls</h4><ul><li>Type safety lost — The compiler won’t stop you from casting to the wrong type.</li><li>Maintenance hazard — A wrong cast might compile fine but cause runtime crashes or data corruption.</li><li>Debugging hell — You can’t tell the original type just by looking at the void*.</li></ul><p>Example — Wrong cast = garbage output</p><pre>int num = 42;<br>void* vp = &amp;num;<br><br>std::cout &lt;&lt; *(static_cast&lt;double*&gt;(vp)) &lt;&lt; &quot;\n&quot;; // ❌ undefined behavior</pre><p>Modern C++ alternatives</p><ul><li>Templates — Type safety with zero runtime cost.</li><li>std::any (C++17) — Type-safe storage for any type, with runtime type checks.</li><li>std::variant (C++17) — A type-safe union of known types.</li></ul><blockquote>💡 Rule of thumb:</blockquote><blockquote><em>Use </em><em>void* only when dealing with low-level C APIs or system calls.<br> In modern C++, templates or type-safe wrappers are almost always better.</em></blockquote><p>Pointers give C++ its speed and low-level power, but they can be tricky. Dangling pointers, wild pointers, memory leaks, and unsafe casts are easy to fall into if you’re not careful. Using nullptr, smart pointers, RAII, and proper type casting helps you stay safe.</p><p>Mastering pointers means understanding memory, ownership, and responsibility — and once you do, you can write code that’s both fast and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d54b530c954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Wand of Polymorphism]]></title>
            <link>https://medium.com/@k10abhilasha/the-wand-of-polymorphism-854782a04c0c?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/854782a04c0c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 11:07:29 GMT</pubDate>
            <atom:updated>2025-07-15T18:03:45.088Z</atom:updated>
            <content:encoded><![CDATA[<p>“One Spell, Many Forms”</p><blockquote>📖Story so far … <br><em>Armed with the </em><strong><em>Shield of Encapsulation</em></strong><em>, draped in the </em><strong><em>Cloak of Abstraction</em></strong><em>, and wielding the mighty </em><strong><em>Sword of Inheritance</em></strong><em>, our hero has traversed the treacherous lands of Objectia. Yet, one challenge remains — facing foes that take many forms, each demanding a different response. To confront these shape-shifting adversaries, the hero must now acquire the </em><strong><em>Wand of Polymorphism</em></strong><em>, a mystical artifact that allows a single call to summon varied responses, based on the true nature of its target</em>.<em> Next up: polymorphic magic. [</em><a href="https://medium.com/@k10abhilasha/the-sword-of-inheritance-c00c72347d46"><em>link</em></a><em>]</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*On_RorzTUS8wA2fVdafVvQ.png" /></figure><p><strong>The Wand of Polymorphism</strong> — a spell which lets objects of different species respond uniquely to the same incantation.</p><p>The final pillar of Object Oriented Programming is polymorphism which lets the user call different function based with same name based on parameters and which object that invokes it.</p><p>Types of Polymorphism —</p><h3><strong>💫 Compile Time Polymorphism (Static Polymorphism)</strong></h3><p><strong>Just like the same wand movement can produce different spells based on the incantation,</strong> <strong>Compile-time Polymorphism</strong> allows the user to call different methods with the same name but different parameter lists. The decision about which method to invoke is made by the compiler at compile time.</p><p>It is typically achieved through:</p><ul><li><strong>Function Overloading:</strong> Defining multiple functions with the same name but different parameter types or numbers.</li><li><strong>Operator Overloading:</strong> Redefining how operators like +, -, or == behave for user-defined types.</li></ul><p>This type of polymorphism improves code readability and allows similar operations to be grouped under a common function name.</p><blockquote><strong>📌 Note:</strong><br> 🔮 <strong>Function overloading cannot be achieved by changing only the return type. </strong>The compiler requires a difference in the <strong>parameter list</strong> to distinguish between overloaded functions.</blockquote><blockquote>🔮 Unlike C++ and Java, <strong>Python does not support compile-time (static) polymorphism</strong> through function overloading.</blockquote><blockquote>If multiple functions with the same name are defined in Python, the latest definition overrides the previous ones. <strong>Operator overloading</strong> is supported in Python using special methods (like __add__, __eq__, etc.), but this is resolved at <strong>run-time</strong>, not compile-time. Function overloading-like behavior in Python can be mimicked using:<strong>-</strong></blockquote><blockquote>1. Default arguments</blockquote><blockquote>2. *args and **kwargs</blockquote><blockquote>3. Type checks within functions</blockquote><blockquote>4. Libraries like functools.singledispatch or multipledispatch for multiple dispatch</blockquote><pre>class Spell {<br>    int power;<br><br>    Spell(int p) {<br>        power = p;<br>    }<br><br>    // Function Overloading: different parameters<br>    void cast() {<br>        System.out.println(&quot;Casting a simple spark spell.&quot;);<br>    }<br><br>    void cast(String element) {<br>        System.out.println(&quot;Casting a &quot; + element + &quot; spell.&quot;);<br>    }<br><br>    // No operator overloading in Java — use method instead<br>    Spell combine(Spell other) {<br>        return new Spell(this.power + other.power);<br>    }<br><br>    public static void main(String[] args) {<br>        Spell fire = new Spell(50);<br>        Spell ice = new Spell(30);<br><br>        fire.cast();<br>        fire.cast(&quot;fire&quot;);<br><br>        Spell combined = fire.combine(ice);<br>        System.out.println(&quot;Combined spell power: &quot; + combined.power);<br>    }<br>}</pre><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Spell {<br>public:<br>    int power;<br><br>    Spell(int p) : power(p) {}<br><br>    // Function Overloading: different parameters<br>    void cast() {<br>        cout &lt;&lt; &quot;Casting a simple spark spell.&quot; &lt;&lt; endl;<br>    }<br><br>    void cast(string element) {<br>        cout &lt;&lt; &quot;Casting a &quot; &lt;&lt; element &lt;&lt; &quot; spell.&quot; &lt;&lt; endl;<br>    }<br><br>    // Operator Overloading: combine spell powers<br>    Spell operator+(const Spell&amp; other) {<br>        return Spell(this-&gt;power + other.power);<br>    }<br>};<br><br>int main() {<br>    Spell fire(50);<br>    Spell ice(30);<br><br>    fire.cast();<br>    fire.cast(&quot;fire&quot;);<br><br>    Spell combined = fire + ice;<br>    cout &lt;&lt; &quot;Combined spell power: &quot; &lt;&lt; combined.power &lt;&lt; endl;<br><br>    return 0;<br>}</pre><pre>class Spell:<br>    def __init__(self, power):<br>        self.power = power<br><br>    # Python doesn&#39;t support native function overloading — use default argument<br>    def cast(self, element=None):<br>        if element:<br>            print(f&quot;Casting a {element} spell.&quot;)<br>        else:<br>            print(&quot;Casting a simple spark spell.&quot;)<br><br>    # Operator Overloading using special method<br>    def __add__(self, other):<br>        return Spell(self.power + other.power)<br><br># Usage<br>fire = Spell(50)<br>ice = Spell(30)<br><br>fire.cast()<br>fire.cast(&quot;fire&quot;)<br><br>combined = fire + ice<br>print(f&quot;Combined spell power: {combined.power}&quot;)<br></pre><p>In the world of OOP, both <strong>function overloading</strong> and <strong>operator overloading</strong> help in achieving compile-time polymorphism (static polymorphism).</p><p><strong>🔮Function Overloading</strong> allows multiple functions with the same name but different parameter lists.</p><ul><li>Supported in <strong>C++</strong> and <strong>Java</strong></li><li>Not natively supported in <strong>Python</strong>. Can be mimicked using <strong>default parameters</strong>, *args, **kwargs, or functools.singledispatch.</li></ul><p><strong>🔮 Operator Overloading</strong> lets you redefine the behavior of operators like + or - for user-defined classes.</p><ul><li>Supported in <strong>C++</strong> using the operator keyword</li><li>Not supported in <strong>Java</strong></li><li>Supported in <strong>Python</strong> via <strong>special methods</strong> (like __add__, __sub__, etc.)</li></ul><p><em>In our example, the </em><em>Spell class uses:</em></p><ul><li><strong>Function overloading</strong> to cast different spells based on parameters</li><li><strong>Operator overloading</strong> (where available) to combine spell powers using the + operator.</li></ul><h3>💫 Run Time Polymorphism (Dynamic Polymorphism)</h3><p>Just like certain ancient spells reveal their true form only when cast, <strong>Run-time Polymorphism</strong> allows a function call to resolve to different implementations at <strong>run time</strong>, based on the actual object that invokes it.</p><p>It enables one common interface (like a method name) to work with objects of different types, each providing its own specific implementation.</p><p>This type of polymorphism is typically achieved through:</p><ul><li><strong>Method Overriding</strong>: A derived class provides a specific implementation of a method that is already defined in its base class.</li></ul><p>In this case, the decision about which method to invoke is made at <strong>run time</strong>, based on the actual type of the object pointed to by a reference or pointer.</p><p>📌 Key Characteristics:</p><ul><li>Function signatures remain the same in both base and derived classes.</li><li>Method selection happens dynamically at run time.</li><li>Enables late binding / dynamic dispatch.</li><li>Commonly used with inheritance and virtual functions (C++) or method overriding (Java, Python).</li></ul><pre>class Creature {<br>    void attack() {<br>        System.out.println(&quot;Creature attacks in a generic way.&quot;);<br>    }<br>}<br><br>class Dragon extends Creature {<br>    @Override<br>    void attack() {<br>        System.out.println(&quot;Dragon breathes fire!&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Creature c = new Dragon();<br>        c.attack();  // Calls Dragon&#39;s attack() at run time<br>    }<br>}</pre><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Creature {<br>public:<br>    virtual void attack() {<br>        cout &lt;&lt; &quot;Creature attacks in a generic way.&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Dragon : public Creature {<br>public:<br>    void attack() override {<br>        cout &lt;&lt; &quot;Dragon breathes fire!&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Creature* c;<br>    Dragon d;<br><br>    c = &amp;d;<br>    c-&gt;attack();  // Calls Dragon&#39;s attack() at run time<br><br>    return 0;<br>}</pre><pre>class Creature:<br>    def attack(self):<br>        print(&quot;Creature attacks in a generic way.&quot;)<br><br>class Dragon(Creature):<br>    def attack(self):<br>        print(&quot;Dragon breathes fire!&quot;)<br><br># Usage<br>c = Dragon()<br>c.attack()  # Calls Dragon&#39;s attack() at run time</pre><blockquote>📌 Note</blockquote><blockquote><strong>Run-time Polymorphism</strong> occurs when the method to be invoked is determined during program execution, based on the actual type of the object.</blockquote><blockquote>Achieved through <strong>virtual functions</strong> in C++, <strong>method overriding</strong> in Java and Python.</blockquote><blockquote>In <strong>C++</strong>, forgetting to make the base method virtual will result in compile-time binding instead of run-time binding.</blockquote><blockquote><strong>Python</strong> uses dynamic typing and method overriding naturally supports polymorphism without extra keywords.</blockquote><blockquote><strong>Java</strong> uses @Override annotation (optional, but recommended) for clarity and error checking.</blockquote><p><em>⚠️</em> <strong>Modern Best Practices:</strong></p><ul><li>Use override / @Override / @override decorators where supported for safer overriding.</li><li>Always declare destructors virtual in C++ when using polymorphism.</li><li>Prefer <strong>composition over deep inheritance trees</strong>.</li><li>Manage memory safely using smart pointers in C++.</li><li>In Python, rely on duck typing and clear documentation, and optionally functools.singledispatch for multiple dispatch.</li></ul><h3>✨ Advantages of Polymorphism in OOP</h3><ol><li><strong>Code Reusability: </strong>Write generic code that can work with different types of objects.</li><li><strong>Flexibility and Extensibility: </strong>New classes can be introduced with minimal changes to existing code.</li><li><strong>Improved Code Maintenance: </strong>Reduces coupling and allows parts of the system to evolve independently.</li><li><strong>Dynamic Behavior: </strong>Method calls are resolved at runtime (in dynamic polymorphism), enabling more adaptable systems.</li><li><strong>Simplified Interface Design: </strong>Use a common interface to interact with multiple object types.</li><li><strong>Eliminates Conditionals and Type Checking: </strong>Avoid if-else or switch-case statements by leveraging polymorphic calls.</li><li><strong>Clean, Readable Code: </strong>Logical grouping of operations under the same method name enhances readability and organization.</li><li><strong>Supports Open/Closed Principle: </strong>Code is open for extension (new subclasses), but closed for modification (no need to alter existing tested code).</li></ol><p>And with the <strong>Wand of Polymorphism</strong> in hand, our hero completes the <strong>OOPS Quest</strong> — mastering the four legendary artifacts: <strong>Encapsulation, Abstraction, Inheritance,</strong> and <strong>Polymorphism</strong>. The kingdom of <strong>Objectia</strong> now stands guarded by clean, reusable, and adaptable code.</p><p>The journey may be over, but the lessons endure in every well-structured program.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=854782a04c0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚔ The Sword of Inheritance]]></title>
            <link>https://medium.com/@k10abhilasha/the-sword-of-inheritance-c00c72347d46?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/c00c72347d46</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 15:06:55 GMT</pubDate>
            <atom:updated>2025-07-01T15:24:04.056Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Powers Passed Through Code Bloodlines”</em></p><blockquote>📖<strong>Story so far …</strong></blockquote><blockquote>In the quest to refactor the kingdom of Objectia, our hero now commands the <strong>Shield of Encapsulation</strong>, safeguarding class state through private fields and controlled accessors. With the <strong>Cloak of Abstraction</strong>, they’ve decoupled interfaces from implementation, reducing system dependencies and hiding internal complexity behind clean, well-defined APIs. The battle against <strong>spaghetti code</strong>, tight coupling, and redundant patterns wages on. Next up: inheritance hierarchies and polymorphic magic. <a href="https://medium.com/@k10abhilasha/the-oops-quest-taming-the-four-pillars-of-code-1a2b71bd2183">[link]</a></blockquote><p><strong>The Sword of Inheritance </strong>— a relic that is passed from generations to generations to use in their own way.</p><p>Inheritance is the third pillar of object oriented programming which helps to reuse code. It enables a child class to acquire methods and fields from parent class , Just like an heir inherits sword from generation and adds their own magic to it and customize it.</p><p>In heritance, a child class inherits<em> public</em> and <em>protected</em> members of parent class.</p><blockquote>In <strong>C++</strong>, programmers must clearly say which abilities (methods) can be changed by child classes by marking them as <em>virtual</em>. If a method isn’t marked, no one can override it. And if a method is marked as <strong>pure virtual</strong> (like a blueprint with no instructions), then every child class is required to create its own version before it can be used.</blockquote><blockquote>In <strong>Java</strong> and <strong>Python</strong>, things are more flexible. All normal methods can be overridden by child classes without needing any special keyword. You only need to mark a method as <em>abstract</em> if you want to force every child class to provide its own version. In Java, you do this inside an <em>abstract class</em> or an <em>interface</em>. In Python, you use something called an <em>abstract base class</em> and a special <em>@abstractmethod</em> decorator.</blockquote><blockquote>So while <strong>C++ makes you decide upfront which methods can be changed</strong>, <strong>Java and Python allow it by default, unless you specifically say otherwise</strong>.</blockquote><p>Types of Inheritance —</p><h3>⚔️<strong>Single Inheritance</strong></h3><p>A single class (warrior) can inherit powers (methods) from only one ancestor class (relic).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*y3j-Kyp8lzX5LCOemHYsxg.png" /><figcaption>Single Inheritance</figcaption></figure><pre>#include&lt;iostream&gt;<br>using namespace std;<br><br>// Base class<br>class Sword {<br>  public:<br>    // Normal method — cannot be overridden<br>    void attack() {<br>        cout &lt;&lt; &quot;Swinging the sword!&quot; &lt;&lt; endl;<br>    }<br>    <br>    // Virtual method — can be optionally overridden<br>    virtual void power() {<br>        cout &lt;&lt; &quot;No power added!&quot; &lt;&lt; endl;<br>    }<br>    <br>    // Pure virtual (abstract) method — must be overridden<br>    virtual void ultimatePower() = 0;<br>};// Derived class<br>class MagicSword : public Sword {<br>  public:<br>    // New method unique to MagicSword<br>    void enchant() {<br>        cout &lt;&lt; &quot;The sword glows with magical power!&quot; &lt;&lt; endl;<br>    }<br>    <br>    // Optional override of virtual method<br>    void power() override {<br>        cout &lt;&lt; &quot;Magic power added to sword!&quot; &lt;&lt; endl;<br>    }<br>    <br>    // Mandatory override of pure virtual method<br>    void ultimatePower() override {<br>        cout &lt;&lt; &quot;Unleashing ultimate magic slash!&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    MagicSword mySword;<br>    // Base class normal method (inherited)<br>    mySword.attack();<br>    // Derived class new method<br>    mySword.enchant();<br>    // Overridden virtual method<br>    mySword.power();<br>    // Overridden pure virtual (abstract) method<br>    mySword.ultimatePower();<br>    return 0;<br>}</pre><pre>abstract class Sword {<br>    void attack() { System.out.println(&quot;Swing sword&quot;); }<br>    void power() { System.out.println(&quot;Basic power&quot;); }   <br>    abstract void ultimatePower();                        <br>}<br>class MagicSword extends Sword {<br>    @Override<br>    void power() { System.out.println(&quot;Magic power&quot;); }<br>    @Override<br>    void ultimatePower() { System.out.println(&quot;Ultimate magic slash!&quot;); }<br>}<br><br>public class MySword {<br>    public static void main(String[] args) {<br>        MagicSword mySword = new MagicSword();<br>        mySword.attack();   // Inherited from Sword<br>        mySword.power();  // Defined in MagicSword<br>        mySword.ultimatePower(); //Defined in MagicSword<br>    }<br>}</pre><pre>from abc import ABC, abstractmethod<br>class Sword(ABC):<br>    def attack(self):<br>        print(&quot;Swing sword&quot;)  # virtual/normal<br>    def power(self):<br>        print(&quot;Basic power&quot;)  # optional override<br>    @abstractmethod<br>    def ultimatePower(self):<br>        pass #must override<br>class MagicSword(Sword):<br>    def power(self):<br>        print(&quot;Magic power&quot;)<br>    def ultimatePower(self):<br>        print(&quot;Ultimate magic slash!&quot;)<br>        <br>if __name__ == &quot;__main__&quot;:<br>    mySword = MagicSword()<br>    mySword.attack()<br>    mySword.power()<br>    mySword.ultimatePower()</pre><h3>⚔️<strong>Multilevel Inheritance</strong></h3><p>A class (warrior) inherits powers (methods) passed down from generations, each generation adding more power to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*eWTnwIf2FnYcsOm-dBNkyQ.png" /><figcaption>Multilevel Inheritance</figcaption></figure><blockquote>Use multilevel inheritance when you have a clear hierarchical relationship where each level builds logically on the previous one. Avoid overcomplicating the chain, as deep inheritance hierarchies can make maintenance harder.</blockquote><pre>/*<br>Multilevel Inheritance — a class (warrior) inherits powers (methods)<br>passed down through generations, with each generation adding new abilities.<br>In this example:<br>- Sword provides basic attack()<br>- Magic inherits from Sword and adds enchant()<br>- UltimateSword inherits from Magic and adds glow()<br>UltimateSword gets access to all abilities passed down the chain.<br>*/<br>#include&lt;iostream&gt;<br>using namespace std;<br>class Sword {<br>public:<br>    void attack() {<br>        cout &lt;&lt; &quot;Swinging the sword!&quot; &lt;&lt; endl;<br>    }<br>};<br>class Magic : public Sword {<br>public:<br>    void enchant() {<br>        cout &lt;&lt; &quot;Casting spells!&quot; &lt;&lt; endl;<br>    }<br>};<br>class UltimateSword : public Magic {<br>public:<br>    void glow() {<br>        cout &lt;&lt; &quot;My sword glows in the dark!&quot; &lt;&lt; endl;<br>    }<br>};<br>int main() {<br>    UltimateSword mySword;<br>    mySword.attack();   // From Sword<br>    mySword.enchant();  // From Magic<br>    mySword.glow();     // From UltimateSword<br>    return 0;<br>}</pre><pre>/*<br>Multilevel Inheritance — a class (warrior) inherits powers (methods)<br>passed down through generations, with each generation adding new abilities.<br>In this example:<br>- Sword provides attack()<br>- Magic inherits from Sword and adds enchant()<br>- UltimateSword inherits from Magic and adds glow()<br>UltimateSword gets access to all abilities passed down the chain.<br>*/<br>class Sword {<br>    void attack() {<br>        System.out.println(&quot;Swinging the sword!&quot;);<br>    }<br>}<br>class Magic extends Sword {<br>    void enchant() {<br>        System.out.println(&quot;Casting spells!&quot;);<br>    }<br>}<br>class UltimateSword extends Magic {<br>    void glow() {<br>        System.out.println(&quot;My sword glows in the dark!&quot;);<br>    }<br>}<br>public class Main {<br>    public static void main(String[] args) {<br>        UltimateSword mySword = new UltimateSword();<br>        mySword.attack();   // From Sword<br>        mySword.enchant();  // From Magic<br>        mySword.glow();     // From UltimateSword<br>    }<br>}</pre><pre>&#39;&#39;&#39;<br>Multilevel Inheritance — a class (warrior) inherits powers (methods)<br>passed down through generations, with each generation adding new abilities.<br>In this example:<br>- Sword provides attack()<br>- Magic inherits from Sword and adds enchant()<br>- UltimateSword inherits from Magic and adds glow()<br>UltimateSword gets access to all abilities passed down the chain.<br>&#39;&#39;&#39;<br>class Sword:<br>    def attack(self):<br>        print(&quot;Swinging the sword!&quot;)<br>class Magic(Sword):<br>    def enchant(self):<br>        print(&quot;Casting spells!&quot;)<br>class UltimateSword(Magic):<br>    def glow(self):<br>        print(&quot;My sword glows in the dark!&quot;)<br># Create an instance and call inherited methods<br>mySword = UltimateSword()<br>mySword.attack()   # From Sword<br>mySword.enchant()  # From Magic<br>mySword.glow()     # From UltimateSword</pre><h3>⚔️<strong>Multiple Inheritance</strong></h3><p>A single class (warrior) can inherit powers (methods) from more than one ancestor class (relic). But it can create a problem known as<strong> Diamond Problem.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*CvY1RWF49fGWOUNsLbtdlQ.png" /><figcaption>Multiple Inheritance</figcaption></figure><p>But not every language in the kingdom allows this power. Some fear its dangers, others embrace it with rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*DOQcX2IqFIUGpB67tnXvTw.png" /><figcaption>Diamond Problem</figcaption></figure><blockquote>Use <strong>multiple inheritance</strong> when a class logically needs to inherit behavior from <strong>multiple independent sources</strong>, and those sources don’t overlap too heavily or conflict often.</blockquote><blockquote><strong>Example:</strong></blockquote><blockquote>A <em>FlyingSword</em> that needs abilities from both <em>Sword</em> and <em>FlightRelic</em>.</blockquote><blockquote>Or a <em>LoggingMixin</em> and <em>DatabaseConnector</em> combined into a class.</blockquote><blockquote>It’s handy when combining small, well-defined, independent behaviors.</blockquote><pre>/*<br>In C++, when multiple base classes override the same virtual method,<br>and a derived class inherits from both, calling the method becomes ambiguous.<br>Even with virtual inheritance (which ensures a single base subobject),<br>the compiler doesn&#39;t know whether to use MagicSword&#39;s or Katana&#39;s version of &#39;attack&#39;.<br>To resolve this, the derived class must explicitly override the method<br>and decide which base class version to call, or provide its own implementation.<br>*/<br>#include&lt;iostream&gt;<br>using namespace std;<br>class sword{<br>public:<br>    virtual void attack() {<br>        cout &lt;&lt; &quot;Swinging Sword&quot; &lt;&lt; endl;<br>    }<br>};<br>class MagicSword: virtual public sword{<br>public:<br>    void attack() override {<br>        cout &lt;&lt; &quot;Attacking with magic sword!&quot; &lt;&lt; endl;<br>    }<br>};<br>class Katana: virtual public sword{<br>public:<br>    void attack() override {<br>        cout &lt;&lt; &quot;Attacking with Nichirin sword!&quot; &lt;&lt; endl;<br>    }<br>};<br>class ultimateSword: public MagicSword, public Katana{<br>    // No override here<br>};<br>int main() {<br>    ultimateSword mySword;<br>    // mySword.attack();  // ❌ Ambiguous: which one — MagicSword or Katana?<br>}<br>/*<br>to overcome this we need to explicitly declare attack in ultimateSword .<br>class ultimateSword : public MagicSword, public Katana {<br>public:<br>    void attack() override {<br>        MagicSword::attack();  // or Katana::attack()<br>    }<br>};<br>*/</pre><pre>/*<br>Java does not support multiple inheritance via class it supports multiple <br>inheritance via interfce, avoiding diamond problem all together.<br>*/<br>interface Sword {<br>    void attack();<br>}<br>class MagicSword implements Sword {<br>    public void attack() {<br>        System.out.println(&quot;Attacking with Magic Sword!&quot;);<br>    }<br>}<br>class Katana implements Sword {<br>    public void attack() {<br>        System.out.println(&quot;Attacking with Nichirin Sword!&quot;);<br>    }<br>}<br>// Since Java can&#39;t inherit both MagicSword and Katana as classes,<br>// we can instead implement Sword directly, and delegate if needed.<br>class UltimateSword implements Sword {<br>    MagicSword magicSword = new MagicSword();<br>    Katana katana = new Katana();<br>    public void attack() {<br>        magicSword.attack();  // or katana.attack();<br>    }<br>}<br>public class Main {<br>    public static void main(String[] args) {<br>        UltimateSword mySword = new UltimateSword();<br>        mySword.attack();<br>    }<br>}</pre><pre>&#39;&#39;&#39; <br>Python supports multiple inheritance via classes, which can cause the<br>diamond problem — when multiple parent classes define the same method.<br>Python resolves this using something called **MRO (Method Resolution Order)**.<br>MRO defines the order in which base classes are searched when calling a method.In the example below, UltimateSword(MagicSword, Katana) means:<br>- Python will first look for attack() in UltimateSword<br>- Then in MagicSword (left to right)<br>- Then in Katana<br>- Then in Sword<br>- And finally in object (the base of all classes)<br>Whichever method it finds first in this order will be called.<br>This avoids ambiguity without needing special keywords like &#39;virtual&#39; (C++) or &#39;interface&#39; (Java).<br>&#39;&#39;&#39;<br>class Sword:<br>    def attack(self):<br>        print(&quot;Swinging Sword&quot;)<br>class MagicSword(Sword):<br>    def attack(self):<br>        print(&quot;Attacking with Magic Sword!&quot;)<br>class Katana(Sword):<br>    def attack(self):<br>        print(&quot;Attacking with Nichirin Sword!&quot;)<br># Multiple inheritance - both MagicSword and Katana inherit from Sword,<br># and UltimateSword inherits from both.<br>class UltimateSword(MagicSword, Katana):<br>    pass<br># Which attack() will be called?<br>mySword = UltimateSword()<br>mySword.attack()  # Will follow Python&#39;s MRO (Method Resolution Order)</pre><h3>⚔️<strong>Hierarchical Inheritance</strong></h3><p>Sword techniques are passed from ancestor(parent class) to multiple children (child class) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*M0jEw0XtUTixvtFFKI88uQ.png" /><figcaption>Hierarchical Inheritance</figcaption></figure><blockquote>Use <strong>hierarchical inheritance</strong> when you have <strong>multiple classes that share common behavior from a single parent</strong>, but also need to define their own unique methods.</blockquote><blockquote><strong>Example:</strong></blockquote><blockquote><em>Vehicle</em> class → inherited by <em>Car</em>, <em>Truck</em>, <em>Bike</em></blockquote><blockquote><em>Sword</em> class → inherited by <em>MagicSword</em>, <em>Katana</em></blockquote><blockquote>It’s a clean way to avoid code duplication while maintaining separate child classes for different behaviors.</blockquote><pre>#include&lt;iostream&gt;<br>using namespace std;<br>class sword{<br>  public:<br>    void ancientTechniques(){<br>      cout&lt;&lt;&quot;Ancient sword swinging technique!&quot;&lt;&lt;endl;<br>    }<br>};<br>class MagicSword : public sword{<br>  public:<br>    void enchat(){<br>      cout&lt;&lt;&quot;Adding magic to ancient technique!&quot;&lt;&lt;endl;<br>    }<br>};<br>class Katana : public sword{<br>  public:<br>    void ninjaTechnique(){<br>      cout&lt;&lt;&quot;Adding ninja technique to the sword!&quot;&lt;&lt;endl;<br>    }<br>};</pre><pre>/*<br>Hierarchical Inheritance — Sword techniques are passed from a single ancestor (parent class)<br>to multiple child classes, each adding their own abilities.<br>In this example:<br>- Sword provides ancientTechniques()<br>- MagicSword inherits from Sword and adds enchant()<br>- Katana inherits from Sword and adds ninjaTechnique()<br>*/<br>class Sword {<br>    void ancientTechniques() {<br>        System.out.println(&quot;Ancient sword swinging technique!&quot;);<br>    }<br>}<br>class MagicSword extends Sword {<br>    void enchant() {<br>        System.out.println(&quot;Adding magic to ancient technique!&quot;);<br>    }<br>}<br>class Katana extends Sword {<br>    void ninjaTechnique() {<br>        System.out.println(&quot;Adding ninja technique to the sword!&quot;);<br>    }<br>}<br>public class Main {<br>    public static void main(String[] args) {<br>        MagicSword myMagicSword = new MagicSword();<br>        Katana myKatana = new Katana();<br>        myMagicSword.ancientTechniques();<br>        myMagicSword.enchant();<br>        myKatana.ancientTechniques();<br>        myKatana.ninjaTechnique();<br>    }<br>}</pre><pre>&#39;&#39;&#39;<br>Hierarchical Inheritance — Sword techniques are passed from a single ancestor (parent class)<br>to multiple child classes, each adding their own abilities.<br>In this example:<br>- Sword provides ancientTechniques()<br>- MagicSword inherits from Sword and adds enchant()<br>- Katana inherits from Sword and adds ninjaTechnique()<br>&#39;&#39;&#39;<br>class Sword:<br>    def ancientTechniques(self):<br>        print(&quot;Ancient sword swinging technique!&quot;)<br>class MagicSword(Sword):<br>    def enchant(self):<br>        print(&quot;Adding magic to ancient technique!&quot;)<br>class Katana(Sword):<br>    def ninjaTechnique(self):<br>        print(&quot;Adding ninja technique to the sword!&quot;)<br># Create objects and use inherited and own methods<br>myMagicSword = MagicSword()<br>myKatana = Katana()<br>myMagicSword.ancientTechniques()<br>myMagicSword.enchant()<br>myKatana.ancientTechniques()<br>myKatana.ninjaTechnique()</pre><blockquote>💡 <strong>Note:</strong> In C++, you can even combine different inheritance types (like multiple and multilevel) in what’s called <strong>hybrid inheritance</strong>. While possible, this often leads to complex, fragile hierarchies and should be approached with caution. Most modern design favors <strong>composition over inheritance</strong> for flexibility and maintainability.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*jglNAAJJzITtHMZJqIyxuw.png" /></figure><blockquote>⚠️ <strong>Modern Best Practice:</strong><br> While inheritance is powerful, overusing it can lead to fragile, tightly coupled hierarchies. Favor <strong>composition</strong> — building classes by combining smaller, focused components — when flexibility and decoupling are priorities.</blockquote><h3>⚔️ Advantages of Inheritance in Your Coding Quest</h3><p>🗡️ <strong>Code Reusability — </strong>You don’t have to rewrite common methods in multiple classes. Shared behavior can live in a parent class and be reused by all its children.</p><p>🗡️ <strong>Improved Maintainability — </strong>When a change is needed (like fixing a bug or improving logic), you only modify it in one place — the base class — and all child classes get the update automatically.</p><p>🗡️ <strong>Logical Hierarchy and Readability — </strong>Inheritance models real-world relationships like <em>MagicSword is-a Sword</em>, making code easier to understand and reason about.</p><p>🗡️ <strong>Supports Polymorphism — </strong>Allows you to write code that works on parent types but behaves differently for each subclass.<br> <em>(You can call </em><em>attack() on a </em><em>Sword, and get different results depending on whether it’s a </em><em>Katana or </em><em>MagicSword.)</em></p><p>🗡️ <strong>Encourages Extensibility — </strong>You can add new functionality in child classes without modifying the existing parent class — promoting open/closed principle (open for extension, closed for modification).</p><p>The journey doesn’t end here. Ahead lies <strong>The Wand of Polymorphism</strong> — the ancient magic that lets swords, katanas, and magic staffs wield their power under a common guise. Stay sharp, adventurer — the final pillar awaits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c00c72347d46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The OOP Quest: Taming the Four Pillars of Code]]></title>
            <link>https://medium.com/@k10abhilasha/the-oops-quest-taming-the-four-pillars-of-code-1a2b71bd2183?source=rss-566dc85d03ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2b71bd2183</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Kabhilasha]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 18:54:46 GMT</pubDate>
            <atom:updated>2025-07-01T15:25:02.346Z</atom:updated>
            <content:encoded><![CDATA[<p>In a land beyond messy spreadsheets and chaotic scripts lies the mystical kingdom of <strong>Objectia</strong> — a realm built not from bricks, but from <strong>classes, objects, and elegant design</strong>.</p><p>For generations, peace reigned under the wisdom of <strong>Object-Oriented Programming</strong>, upheld by four ancient pillars. But now, a terrible beast has awakened: the <strong>Legacy Bug</strong> — a dragon born from tangled code, unchecked variables, and forgotten best practices.</p><p>And so, a new hero must rise.</p><p><strong>You.</strong></p><p>Armed with curiosity and a compiler, you must master the Four Pillars of OOP:</p><p>🛡️ The Shield of <strong>Encapsulation</strong></p><p>🎭 The Cloak of<strong> Abstraction</strong></p><p>⚔️<strong> </strong>The Sword of<strong> Inheritance</strong></p><p>🪄 The Wand of <strong>Polymorphism</strong></p><p>Only by claiming these relics can you tame the Legacy Bug and restore harmony to the Kingdom of Code.</p><p>So grab your keyboard, adventurer — <strong>your quest begins now.</strong></p><h3><strong><em>📌 The Shield of Encapsulation</em></strong></h3><p><em>“Protecting Your Code’s Secrets”</em></p><p><strong>Shield of Encapsulation</strong> — a relic that guards internal data from meddling hands. It keeps the treasure safe by appointing loyal guards only through which the treasures can be accessed.</p><p>Encapsulation is the first pillar of OOP which helps to guard the data of class by using access modifiers. It <strong>protects the internal state and enforce controlled interaction using public methods</strong>. Just like a castle treasury is guarded by loyal knights.</p><p>It is achieved using</p><ul><li><strong>Declaring data members as private or protected</strong> so they cannot be accessed directly.</li><li><strong>Providing public methods (getters and setters)</strong> to control access to those data members.</li></ul><pre>class CastleTreasury{<br>    private:<br>        int goldCoins = 2000;<br>    public:<br>        void addCoins(int coins){<br>          //Logic to add coins to Treasury<br>        }<br>        int getCoins(int coins){<br>          //Request coins needed by proving number of coins<br>        }<br>};</pre><pre>class CastelTreasury{<br>    private int goldCoins = 2000;<br>    <br>    //method to add coins to Treasury<br>    public void addCoins(int coins){<br>        //Logic to add coins<br>     }<br>    <br>    //method to ask coin from treasury<br>    public int getCoins(int coins){<br>         //Logic to ask coins<br>    }<br>}</pre><pre>class castelTreasury:<br>  __goldCoins : int = 2000<br>  <br>  #method to add coins to treasury<br>  def addCoins(self,coins :int) -&gt; None:<br>    #logic to add coins<br>    pass<br><br>  #method to ask coins<br>  def getCoins(self,coins : int) -&gt; int:<br>    #logic to ask coins<br>    pass</pre><p>Benefits of encapsulation in your coding quest —</p><p>🛡️Protects sensitive data from unauthorized access.</p><p>🛡️Provides validation logic inside setter function to avoid invalid value.</p><p>🛡️ Provides controlled, predictable interactions with an object’s state.</p><p>🛡️Improves maintainability by reducing the risk of accidental access and modification of data.</p><blockquote>🧝‍♂️Pro tip : <br>Encapsulation is not just about hiding data — it’s about preserving <strong>invariants</strong>. The class should stay in a valid, consistent state at all times.</blockquote><pre>//bad code design<br>void addCoins(int coins) { goldCoins += coins; } // Direct, unsafe</pre><blockquote>It can lead to unwanted behavior when negative coins are passed will lead to decrease the number of coins instead of increasing it</blockquote><pre>//better design<br>void addCoins(int coins){<br>  if (coins &gt; 0)<br>    goldCoins += coins;<br>}</pre><p>Without this shield, careless sorcerers (or developers) might meddle with your gold directly — leaving your treasury (and program) vulnerable. Encapsulation is your code’s first line of defense. By declaring data as private and controlling access through methods, you safeguard your program’s state while providing clean, reliable ways for other parts of your system to interact with it.</p><blockquote>Your online banking app won’t let you arbitrarily set your account balance to ₹1,00,000 — it lets you deposit or withdraw via secure, validated operations.</blockquote><p>✅ <strong>Best Practice:</strong><br> 👉 Keep your class invariant safe — meaning your object should never be in an invalid state. Use validations inside setters / methods.</p><p>✅ <strong>Best Practice:</strong><br> 👉 If a class has only one responsibility and no external entity needs to touch its fields, prefer no getters/setters at all. Avoid overengineering.</p><p>❌ <strong>Anti-pattern:</strong><br> 👉 <strong>Data Clumps</strong> — when multiple classes expose and access the same group of data fields independently. Bundle related data and logic together.</p><h3>🧝‍♀️The Cloak of Abstraction</h3><p><em>“Hide the Mess, Show the Magic”</em></p><p><strong>The cloak of abstraction</strong> — magical garment which hides the messy chaos beneath and only shows what is important.</p><p>Abstraction is the second pillar of object oriented programming which helps to hide the details of implementation whilst providing essential details or user feature. It focuses on what a spell (object) does instead of how it do it, thereby reducing complexity and increasing efficiency. Simply put —<strong> Just let me cast the spell don’t tell me how it works</strong>.</p><p>Abstraction can be achieved using</p><ul><li><strong>Interfaces </strong>— define the essential methods and leave the implementation to the derived class.</li><li><strong>Abstract classes</strong> — declare the method with signature without implementation forcing the derived class to implement them.</li><li><strong>Access modifiers </strong>— Hide the unnecessary detail (private, protected) and expose only the essential feature (public).</li><li><strong>Polymorphism — </strong>Allows treating different object types through a common abstract interface, focusing on behavior.</li></ul><pre>class Spell{<br>  public:<br>    virtual void castSpell() = 0; //pure virtual function<br>};<br><br>class FireSpell : public Spell{<br>  public:<br>    void castSpell () override {<br>        // Logic for fireSpell<br>        cout&lt;&lt;&quot;Casting Firespell!&quot;&lt;&lt;endl;<br>    }<br>};</pre><pre>interface Spell{<br>  void castSpell();<br>}<br><br>class FireSpell implements Spell{<br>    public void castSpell(){<br>        //Logic for firespell<br>        System.out.println(&quot;Casting Fireball !&quot;);<br>    }<br>}</pre><pre>from abc import ABC, abstractmethod<br><br>class Spell(ABC):<br>    @abstractmethod<br>    def castSpell(self):<br>        pass<br><br>class Fireball(Spell):<br>    def castSpell(self):<br>        #Logic for firespell<br>        print(&quot;Casting Fireball!&quot;)</pre><p>Benefits of abstraction in your coding quest —</p><p>🎭 Reduces dependency between systems.</p><p>🎭 Hides implementation details and complexity.</p><p>🎭 Improves code readability and maintainability.</p><p>🎭 Helps to increase security as only necessary details are exposed to user.</p><blockquote><strong>💡 Did You Know?</strong><br> Abstraction isn’t exclusive to OOP — operating systems, web APIs, and databases abstract away internals while offering simple, clear interfaces.</blockquote><p><strong>When to use Interface vs Abstract Class:</strong></p><ul><li>Use an <strong>interface</strong> when you want to define a contract that unrelated classes can implement.</li><li>Use an <strong>abstract class</strong> when you want to share common code and enforce behavior.</li></ul><blockquote>You don’t need to know how your coffee machine brews — just which button to press.</blockquote><p>✅ <strong>Best Practice:</strong><br> 👉 Interfaces should define <strong>behavioral contracts</strong>, not data structures.</p><p>✅ <strong>Best Practice:</strong><br> 👉 Keep abstractions stable — minimize changes to interfaces once published. Evolving abstraction contracts breaks dependent code.</p><p>✅ <strong>Best Practice:</strong><br> 👉 When designing abstractions, think from the consumer’s perspective first:<br> <em>“What will they care to see? What is noise?”</em></p><p>❌ <strong>Anti-pattern:</strong><br> 👉 Avoid exposing unnecessary configuration or setter methods on abstract classes/interfaces. Keep the API lean.</p><p>❌ <strong>Anti-pattern:</strong><br> 👉 Avoid coupling abstractions to concrete classes. Favor Dependency Injection or Factory patterns when creating concrete instances of abstractions.</p><h3><strong>Difference between encapsulation and abstraction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*w0dsW7AfLs4H4LcUMC7UoQ.png" /></figure><blockquote>Encapsulation and abstraction aren’t opposites — they’re allies. Encapsulation hides <em>how</em>, abstraction hides <em>what</em>. Good design balances both.</blockquote><p>We’ve secured the Shield and donned the Cloak — but the Sword and Wand still lie ahead. Take a breather, warrior. <a href="https://medium.com/@k10abhilasha/the-sword-of-inheritance-c00c72347d46">[Part 2 ]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2b71bd2183" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>