<?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 Dalou Kalaivendhan on Medium]]></title>
        <description><![CDATA[Stories by Dalou Kalaivendhan on Medium]]></description>
        <link>https://medium.com/@daloukalai?source=rss-86132a4da462------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*388a_AGZO3k40SjgrLlKgQ.jpeg</url>
            <title>Stories by Dalou Kalaivendhan on Medium</title>
            <link>https://medium.com/@daloukalai?source=rss-86132a4da462------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:48:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daloukalai/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[AI Writes Code in 5 Minutes but Costs More Time Than Manual Coding”? I Strongly Disagree.]]></title>
            <link>https://medium.com/@daloukalai/ai-writes-code-in-5-minutes-but-costs-more-time-than-manual-coding-i-strongly-disagree-86f4d890292e?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f4d890292e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 13:12:27 GMT</pubDate>
            <atom:updated>2026-02-06T13:12:27.437Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, I’m seeing an increasing number of posts claiming that AI generates code in 5 minutes, but developers then fall into a <strong><em>vicious cycle</em></strong> and end up spending more time fixing it — while developing <strong>without AI supposedly takes less time.</strong></p><p>Honestly?<br>This is funny — and I <strong>strongly disagree.</strong></p><p>I’ve been using <strong>Cline / Claude / Cursor </strong>for quite a long time, and my usage has only increased in recent months. The problem isn’t AI. The problem is how we use it and who uses it.</p><p>Here’s a simple but effective approach that actually works.</p><h3>Part 1: Why Junior Engineers Should Limit AI Usage (Initially)</h3><p>This may sound unpopular, but:</p><p><strong>Ask junior engineers not to rely heavily on tools like Cline or Claude or Cursor.</strong></p><p>There are a couple of important reasons:</p><ol><li><strong>Their learning curve gets compromised</strong><br>Over-dependence on AI shortcuts prevents them from building strong fundamentals.</li><li><strong>Shallow system understanding leads to poor prompts</strong><br>Without deep knowledge of components and data flow, their prompts often result in solutions that require excessive chunks, churns, and rewrites.</li></ol><p>AI doesn’t replace understanding — <br><strong>it amplifies whatever understanding already exists.</strong></p><h3>Part 2: Where AI Truly Delivers Value — Experienced Engineers</h3><p>Now comes the real magic.</p><p>As a <strong>well‑experienced engineer</strong> with:</p><ul><li>Complete understanding of system design</li><li>Clear knowledge of the existing codebase</li><li>Strong intuition around trade-offs</li></ul><p>…this is where you should <strong>start vibing with AI</strong>.</p><p>Let’s be clear:</p><blockquote><strong>Prompt engineering cannot be “learned” separately.<br>It naturally comes from deeply understanding the system.</strong></blockquote><p>When you truly understand the system:</p><ul><li>Your prompts are <strong>healthy, detailed, and comprehensive</strong></li><li>You know <strong>what to accept and what to reject</strong></li><li>You <strong>guide the AI</strong> instead of blindly trusting it</li></ul><p>I approach as below (Visualize it like a <strong>Decorator Pattern)</strong>:</p><ul><li>Vibe the core functionality first</li><li>Test it</li><li>Gradually build additional features around it</li></ul><p>The result?</p><p>✅ Working, high-quality code in <strong>~30 minutes</strong><br>✅ Code that would realistically take <strong>days (or even a week)</strong> to develop manually</p><p>After that:</p><ul><li>Fix minor bugs</li><li>Create a branch</li><li>Switch back to high-value work like <strong>design, reviews, security, and planning.</strong></li></ul><p>That’s real productivity.</p><h3>Final (and Most Important) Part: Closing the Loop with Junior Engineers</h3><p>Here’s the most underrated step.</p><p>Once the branch is ready, <strong>hand it over to junior engineers</strong> to enhance and refactor.</p><p>The advantages are huge:</p><ol><li>They learn <strong>how to refactor real-world code</strong></li><li>They understand <strong>why certain libraries were chosen</strong></li><li>They experiment by <strong>alternating libraries and evaluating trade-offs</strong></li><li>They try to create <strong>leaner code and alternate algorithms</strong></li><li>Most importantly, they do all this <strong>with minimal help — and within timelines</strong></li></ol><p>This creates:</p><ul><li>Better engineers</li><li>Cleaner code</li><li>Faster delivery</li><li>Smarter AI adoption</li></ul><h3>Final Thought</h3><p>AI doesn’t slow teams down.<br><strong>Poor understanding and misuse do.</strong></p><p>Used correctly, AI gives experienced engineers <strong>leverage</strong> — and helps junior engineers grow when used at the right stage.</p><p>Curious to hear how others are structuring AI usage across senior and junior teams. 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f4d890292e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memories of “Pointers”]]></title>
            <link>https://medium.com/@daloukalai/memories-of-pointers-1bbae29625b5?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bbae29625b5</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[shared-pointer]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <category><![CDATA[weak-pointer]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Tue, 03 May 2022 15:27:49 GMT</pubDate>
            <atom:updated>2022-05-04T05:34:26.195Z</atom:updated>
            <content:encoded><![CDATA[<p>This is PART 3 of my modern C++ series. Part 1 &amp; 2 links are below. If you haven’t gone through it, please have a look.</p><ul><li><a href="https://medium.com/@daloukalai/a-few-modern-c-syntax-you-must-adapt-48fbd5996743">A few modern C++ syntax you must adapt!</a></li><li><a href="https://medium.com/@daloukalai/a-few-modern-c-syntax-you-must-adapt-part-ii-3bc840450667">A few modern C++ syntax you must adapt — PART II</a></li></ul><p>Straight to the point, in Part 3 we are going to discuss about pointers in detail. <strong><em>Pointers are the boon and curse of C++</em></strong>. Unlike nowadays, in those times there were only <strong>raw </strong>pointers. As the name says, it is raw and cruel enough to crash and exhaust an application out of memory. In good old college days, people were scared to learn and use it (that includes me too) and safely incline towards Java. As the time pass by, we got <strong>smart pointers</strong> like <strong>shared_ptr</strong>, <strong>weak_ptr</strong>, <strong>unique_ptr </strong>and the deprecated <strong>auto_ptr</strong>. Even now, people think twice to use C++ for “Application Development” because of the possibility of memory leaks. But I tell you, memory leak problem can be easily avoided by smart pointers and C++ today is ultra modern like any programming languages in business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E955ZT3rxgAg4IwO" /><figcaption>Photo by <a href="https://unsplash.com/@umby?utm_source=medium&amp;utm_medium=referral">Umberto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Memory basics</strong></blockquote><p>If I need to talk about pointers, I think I need to start from <strong><em>stack and heap memory</em></strong>. No wait.. Let me start from “<strong><em>memory</em></strong>” actually. A Memory/RAM (Random Access Memory) is the place where an “Executable part of a program” resides during the time of program execution. Memory is actually divided into various segments for multiple purposes; but at present let’s consider <strong>stack and heap segment</strong>. The stack segment will <em>majorly </em>carry memory allocations of those local variables\objects defined inside your program. The nature of stack segment is auto winding and clearing the memory held by it. Thus, when a scope of a function ends, it will unwind the stack and clears them off. There is no possibility of leaving any memory held by it, uncleared.</p><p>The next interesting one is the <strong>heap memory</strong>. It is a “<strong><em>shrink and grow</em></strong>” memory. It can take allocations and keep growing until you reach a predefined MAX heap size on your RAM. Beyond that if you try to expand, it will overflow and crash the program. Now, the interesting question arises. Who is dynamically allocating data inside the heap, maintains it’s life cycle and delete it once the scope is over? <strong><em>It’s YOU!</em></strong> There is no automatic unwinding like stack memory segment.</p><p>But how a user can do it? There are 2 paired ways in C\C++. <strong><em>malloc&amp;free</em></strong> is the old way and then <strong><em>new&amp;delete</em> </strong>is the latest way. <em>Malloc()</em> or <em>new()</em> will allocate memory chunks in heap. <em>Free()</em> or <em>delete()</em> will de-allocate the memory. <strong><em>For every malloc() you should call free() and for every new() you should call delete(). If you do it perfectly, then there is no memory leak, no hassle.</em></strong> Simple, right? But it is not as simple as you think. We will discuss later on why there is possibility that we definitely, accidentally miss it many times. At present let us assume, you missed de-allocation. This will lead to memory leak. This leak would grow faster sometimes (For example, if the allocation is in loop), takes up entire MAX heap location and program will crash in quick time.</p><p><em>*In this article we use new&amp;delete examples and not malloc&amp;free, as they are latest and more powerful than latter.</em></p><blockquote><strong>What is POINTER, then?</strong></blockquote><p>When we allocate a memory in heap using malloc/new, how do we track it and how we can delete it later? It is using pointers. After allocation of memory in heap, malloc/new would return a memory address. Pointer is the logical entity which can hold that. So in simple terms, pointers are the ones which holds <strong>memory address</strong>. It carries a special syntax of “*” before the variable name of the data type of memory it holds.</p><pre>char <strong>*</strong>singleMemoryAddr = new char;<br>char <strong>*</strong>continuousMemoryAddr = new char[10];<br>*(continuousMemoryAddr+5) = &#39;s&#39;; // assign 5th location with &#39;s&#39;<br>...</pre><pre>...<br>delete singleMemoryAddr;<br>delete[] continuousMemoryAddr;</pre><p>In the above code we have 2 scenarios; First <em>new</em> call will allocate 1 Byte(Char is 1 byte in most compilers) in heap. Second <em>new </em>call will allocate 10 continuous Bytes (10*1) in heap. Both the new allocation will return “the start” of the memory address. So from the program’s perspective both pointers would hold a single memory address. But from the usage perspective, you can increment the latter one and access till 10 bytes. When you try the same in with first one, it will go “out of boundary”. Also notice, you use different syntax of <em>delete/delete[] </em>to de-allocate the memory pointed by them.</p><p>Likewise, you can hold start address of <strong><em>any data type,</em></strong> including custom data like class/struct/unions. One difference is, when you increment, it will jump the “<strong>size of your data type</strong>” and not 1 byte like above. Thus pointers are very powerful as it gives direct access to the memory location. If used perfectly, you can do wonders. As you can see, pointers holds the entry point of a heap memory location and you should not lose track of it.</p><p><em>*Remember, pointers are not necessarily to hold only heap memory address as explained. Like below, it can just hold address of stack segment variable too. For that matter we can assign any variable’s address to pointer; the syntax is to add “</em><strong><em>&amp;</em></strong><em>” before that variable. Leaving all that aside, why I am building my article around heap memory is that, the leaks and problems are explained better with it.</em></p><pre>int a = 5;<br>int *p = <strong>&amp;</strong>a;</pre><blockquote><strong>Simple illustration of memory leak</strong></blockquote><pre>void func()<br>{<br>   //Dynamically allocated 100 chars<br>   char* ptr = new char[100];<br>   intermediateFunc();      <strong>// may throw exception</strong><br>   delete[] ptr; // okay if no exception<br>} // memory leak if intermediateFunc() throws exception</pre><p>So in the above example, it looks like we called <em>delete</em> for <em>new</em> and there is no problem. <strong><em>But remember, when an intermediate function is called, the instruction will go to that function and sometimes it will not comes back if there is any exception thrown in that function.</em></strong> Thus keep in mind, though you promptly call delete(), there is a chance that your program might not reach there. It would lead to “<strong>Memory Leaks</strong>”. It will ultimately crash the program at some point of time.</p><blockquote><strong>Smart pointers — The saviors!</strong></blockquote><p>Now you found the problem; though you call <em>delete</em>(), there is no guarantee that it might reach, unless you have take care of all corner cases of possible code paths. But unfortunately, it is very hard to predict all code paths. So, the best way to attack this problem is to “<em>mandate deletion while creation</em>” itself. I mean, at the time of allocation itself, you infuse a smart technique which tracks the pointer and deletes it when going out of scope.We call it as “<strong>Smart pointers</strong>”and this technique is called “<strong>Resource Acquisition Is Initialization (RAII)</strong>”. With the use of templates, it is actually easy to wrap “raw” pointers and write you own smart pointers which does automatic resource de-allocation. But there is no need for it. In modern C++, you have arsenal of smart pointers.</p><p><em>*Elaborating more on RAII and writing our own smart pointer would be an over kill for this article. I better keep it for my next article.</em></p><p>As of today, we totally have 4 smart pointers in C++11:</p><ul><li><strong><em>Shared Pointers.</em></strong></li><li><strong><em>Weak Pointers.</em></strong></li><li><strong><em>Unique Pointers.</em></strong></li><li><strong><em>Auto Pointers (Deprecated).</em></strong></li></ul><blockquote><strong>Raw pointers and it’s usage in common scenarios</strong></blockquote><p>Before getting into smart pointers, let me illustrate what best you can do with raw pointers.</p><ol><li>Assign and point to some memory location.</li></ol><pre>char *p1 = new char(&quot;Hello World&quot;);</pre><p>2. Make one more “raw” pointer point to the <strong>same </strong>memory location.</p><pre>char *p2 = p1;</pre><p>3. Let <strong>more </strong>pointers point to the same memory location.</p><pre>char *p3 = p2;</pre><p>4. Later, reassign one of the pointer to point to some other memory location.</p><pre>p3 = new char(&quot;My world is changed&quot;);</pre><p>5. Release the memory only after making sure ALL the pointers pointing to the memory location goes out of scope.</p><pre>// p3 is already assigned somewhere else.<br>p2 = null; // make sure p2 is unassigned and not &quot;dangling&quot;.<br>delete[] p1; // then delete p1</pre><p>So if you get the whole sense of “raw” pointers above,</p><p>a) A single memory location is not necessarily pointed by only one pointer.</p><p>b) Even if one pointer goes out of scope, the memory can still be valid as it is pointed by few other pointers.</p><p>c) You should delete the pointer only after making sure that all other pointers are taken care for “<em>dangling</em>” condition ( In the above example, <em>p2</em> would be a “<strong><em>dangling pointer</em></strong>”, if you have not assigned it to NULL).</p><blockquote><strong>1. Shared Pointers — The Smart pointer of most use case.</strong></blockquote><p>When you want to learn smart pointers, “<strong>Shared Pointers</strong>” are the No 1 choice; It represents “raw” pointers in the closest possible way. So if you are lazy and want to learn only about one variant of smart pointers, you learn “Shared Pointers” and move on. Unless you are working on memory constraint environment (Share pointers take <strong><em>twice </em></strong>the size of raw pointers), share pointers are the way to go.</p><p><strong>Shared_ptr </strong>as the name suggests shares the responsibility among other pointers and is the right fit for “raw” pointers.<strong> </strong>It could achieve all those 5 points of “Raw Pointers” in smart way i.e., using RAII and destructs only when all objects goes out of scope.</p><p>Especially, the 5th point is achieved by a mechanism called “<strong><em>Reference Counting</em></strong>”. It is a mechanism of maintaining a counter which keep tracks of number of pointers currently assigned to a memory location. The object destruction would be called only when the counter becomes 0. Because of this additional overhead, shared pointer size is twice the size of “raw” pointer.</p><pre><strong>Usage (declaration):</strong><br>std::shared_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName</em></strong>;</pre><pre><strong>Some examples:</strong><br>std::shared_ptr&lt;int&gt; int_sptr;  <strong>// int shared pointer</strong></pre><pre>template&lt;typename T&gt;<br>std::shared_ptr&lt;T&gt; template_sptr; <strong>// template shared pointer</strong></pre><pre>std::shared_ptr&lt;Base&gt; base_sptr; <strong>// used defined class shared ptr</strong><br></pre><p>While assigning a value, always use <strong><em>make_shared</em></strong> function as below.</p><pre><strong>Usage (value assignment):</strong><br>std::shared_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName</em></strong>(new <strong><em>dataType</em></strong>(<strong><em>value</em></strong>)); //(OR)<br>std::shared_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName </em></strong>= make_shared&lt;<strong><em>dataType</em></strong>&gt;(<strong><em>val</em></strong>);</pre><pre><strong>Example:</strong><br>std::shared_ptr&lt;<em>int</em>&gt; <em>int_sptr1</em>(new <em>int</em>(<em>5</em>)); <strong>// Avoid this syntax</strong><br>std::shared_ptr&lt;int&gt; int_sptr2 = make_shared&lt;int&gt;(5);<strong>//use this one</strong><br>cout &lt;&lt; *int_sptr2 &lt;&lt; endl;<strong> // de-reference and print it</strong></pre><pre><strong>// You CAN copy/assign any other shared pointers. <br>// Here, int_sptr1 is destructed and int_sptr2 is reassigned.<br>int_sptr2 = int_sptr1;</strong></pre><blockquote><strong>2. Unique Pointers — The next useful smart pointer</strong></blockquote><p>Though <strong>shared_ptr </strong>solved most of the problems, it comes with a price. The size of the pointer takes twice the size of “raw” pointers. It is mainly because of the “reference counting” mechanism present with it. As I already told you, without referencing counting “shared”ownership cannot be achieved.</p><p>Now, let’s pause for a second and think about it. Do you really need a “Shared” ownership kind of a pointer in your program? <em>The answer depends entirely on you.</em></p><p>Let’s say you follow a programming principle; whenever a pointer is assigned to a memory location, it is the only owner and there is no other pointer point to it <em>i.e.,</em> you always enforce “Exclusive” ownership on some part of your design. Now, let me ask the same question again. Do you really need a “Shared” ownership kind of a pointer in your program? <em>The answer is No, not necessarily!</em></p><p>Interestingly, you would meet this kind of design many a times. It is very common that, we would like to use an “exclusive” pointer and will not allow many pointers point to same memory location. For instance, think about “Factory Method”. You would create objects of a particular type and there is no need that it would be shared as per design. For such situation, we can use a smart pointer called “<strong><em>Unique pointers</em></strong>”. The additional bonus is that you do not have burden of “reference counting” and thus the <strong><em>unique_ptr is same size as “Raw” pointer</em></strong>. Wow! You got a smart pointer of the same size of “raw” pointers. Isn’t that amazing?</p><p>Usage is almost similar to shared pointer:</p><pre><strong>Usage (declaration):</strong><br>std::unique_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName</em></strong>;</pre><pre><strong>Some examples:</strong><br>std::unique_ptr&lt;int&gt; int_uptr;  <strong>// int unique pointer</strong></pre><pre>template&lt;typename T&gt;<br>std::unique_ptr&lt;T&gt; template_uptr; <strong>// template unique pointer</strong></pre><pre>std::unique_ptr&lt;Base&gt; class_uptr; <strong>// used defined class unique ptr</strong></pre><p>Similar to shared_ptr, while assigning a value, always use <strong><em>make_unique</em></strong> function as below.</p><pre><strong>Usage (value assignment):</strong><br>std::unique_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName</em></strong>(new <strong><em>dataType</em></strong>(<strong><em>value</em></strong>)); //(OR)<br>std::unique_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName </em></strong>= make_unique&lt;<strong><em>dataType</em></strong>&gt;(<strong><em>val</em></strong>);</pre><pre>Example:<br>std::unique_ptr&lt;<em>int</em>&gt; <em>int_uptr1</em>(new <em>int</em>(<em>5</em>)); <strong>// Avoid this syntax</strong><br>std::unique_ptr&lt;int&gt; int_uptr2 = make_unique&lt;int&gt;(5); <strong>// Use this</strong><br>cout &lt;&lt; *int_uptr2 &lt;&lt; endl;<strong> // de-reference and print it</strong></pre><p>But remember, you can’t assign or copy like shared pointers. The reason is obvious; You cannot make 2 or more pointers point to same memory location. However, you can “move” the pointers. (<em>If you cannot understand what is “move”, I insist you to read my PART 2 article.</em>)</p><pre><strong>// You CANNOT copy/assign other unique pointers. <br></strong>int_uptr2 = int_uptr1; <strong>// ERROR!! ILLEGAL<br>//However, you can move<br></strong>std::unique_ptr&lt;int&gt; other_uptr;<strong><em><br></em></strong>other_uptr(<strong>std::move</strong>(int_uptr2));</pre><blockquote><strong>3. Weak Pointers — You may rarely in need of it</strong></blockquote><p>Before getting into this concept, remember one thing clearly. <strong><em>There is no “Weak pointers” without “Shared pointers”.</em></strong> It is dependent on “Shared pointers” even on it’s usage. They are so weak. It is weaker to the extent that you can’t even de-reference the value pointed by it. That’s why it is called “Weak Pointers”.</p><pre>Usage:<br>std::weak_ptr&lt;<strong><em>dataType</em></strong>&gt; <strong><em>variableName</em></strong>;</pre><pre>Example:<br>std::weak_ptr&lt;<em>int</em>&gt; <em>wptr</em>;</pre><p>You can’t directly assign a value. It can only point to shared_ptr’s value. In fact, <em>there is </em><strong><em>NO make_weak</em></strong><em> similar to make_unique and make_shared</em>. Also, you can’t de-reference and print the value.</p><pre>weak_ptr&lt;int&gt; wptr(new int(14)); <strong>// ERROR, ILLEGAL!!</strong><br>weak_ptr&lt;int&gt; wptr = make_weak&lt;int&gt;(14); <strong>// ERROR, AGAIN!!</strong></pre><pre>std::shared_ptr&lt;int&gt; sptr = make_shared&lt;int&gt;(14);<br>wptr = sptr; <strong>// LEGAL! you can only point to shared_ptr&#39;s value.</strong></pre><pre>cout &lt;&lt; *wptr; <strong>// ILLEGAL! you can&#39;t dereference it&#39;s value.</strong></pre><p>You must be like “<em>Wait! I am having a pointer which completely depends on shared pointer and I can’t even de-reference it. Then why the heck I need it. Why can’t I use the Shared pointer itself?</em>”. I can hear you well. Below are the 2 use cases where you cannot use “Shared Pointers”. It’s for those purposes.</p><ol><li>When <strong><em>you want to have ownership of the “data alone” and not the complete object ownership</em></strong> for some <strong><em>*purpose</em></strong>. This you cannot achieve just with “Shared Pointers” . Let me illustrate this.</li></ol><p><em>*If I get to explain purpose, you would get lost in it. Don’t worry; you would eventually hit one when you program exhaustively on caching and transient data pointers. Until then, assume there is a purpose.</em></p><pre><strong><em>// 1. takes complete ownership of entire pointer obj pointing to <br>//  value 10. We know it is done by shared_ptr</em></strong><br>    std::shared_ptr&lt;int&gt; sptr;<br>    sptr.reset(new int);<br>    *sptr = 10;</pre><pre><strong><em>// 2. Takes ownership of data alone i.e., the value 10 <br>// It is done only through weak_ptr </em></strong><strong> </strong><br>    std::weak_ptr&lt;int&gt; wptr = sptr;<br><br><strong><em>// 3. Delete existing managed object, acquire new pointer object <br>// You know shared_ptr can reset and acquire new object altogether.</em></strong><br>    sptr.reset(new int);<br>    *sptr = 5;</pre><pre><strong><em>// 4. Now the real use. How can you check if original object pointed to value 10 is deleted? It is only using weak_ptr.<br>// See wptr is (the data pointed by the object) expired, <br>// even though sptr is not expired. <br>// You can either use expired() or lock() function. <br>// Expired() returns bool, while lock() return the value of object.<br>// Avoid expired() when you use thread programming.</em></strong><em><br>// if(wptr.expired())</em></pre><pre>    if(auto tmp = <strong><em>wptr.lock()</em></strong>)<br>        std::cout &lt;&lt; &quot;wptr value is &quot; &lt;&lt; *tmp &lt;&lt; &#39;\n&#39;;<br>    else<br>        std::cout &lt;&lt; &quot;wptr is expired\n&quot;;<br>    </pre><p>2) When you want cyclic dependency for some <strong><em>purpose </em></strong><em>(* This purpose is very rare)</em>. For Example, shared_ptr A and shared_ptr C points to shared_ptr B. Let us assume a case; You also want shared_ptr B to point back to shared_ptr A.</p><p>Something like this: <strong>A →←B ←C</strong></p><p>The choice of A &amp; B as shared_ptr, will make the reference count as 1 always and it can’t be destroyed. Moreover, the life of C is hell as it points to B without depending on A. The solution for this is to declare B as weak_ptr. Think on! It will solve all the problems.</p><blockquote><strong>4. Auto Pointers — Don’t use! Explaining for the sake of completion</strong></blockquote><p>Auto Pointers are “<em>fast cooked</em>” Unique Smart Pointers early in the days of C++98. There are lots of usage restrictions; Especially when used with STL containers. It is because C++98 does not have “Move Semantics” (Refer Part 2 article of mine). So, they had mimicked “Move” with the help of available “Copy Semantics” in C++98. What a weird idea!</p><p>I insist you — You do not need <strong><em>auto_ptr</em></strong> unless you are still stuck with<strong><em> </em></strong>C++98 compiler. Just do a plain “search” and “replace” it with “<strong><em>unique_ptr</em></strong>” in your code. Unique pointer would do everything what you have achieved with auto_ptr in much cleaner way.</p><blockquote><strong>Conclusion</strong></blockquote><p>Now you know that smart pointers connects the two distant worlds; One argues memory management had to be done by machine and the other argues the importance of predictable timing of destruction and thus memory can be better managed self. Smart pointers smartly connects both of them. Even if I leave that side of argument; <em>In modern C++ programming, you must know smart pointers and use them instead of raw pointers</em>. Hope you got some clarity in this article. That is all for now. Catch ya all in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bbae29625b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT — Minimum commands to work like professional — Part 2]]></title>
            <link>https://faun.pub/git-minimum-commands-to-work-like-professional-part-2-d63a0485759a?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/d63a0485759a</guid>
            <category><![CDATA[git-command-line]]></category>
            <category><![CDATA[git-basics]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-commands]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 07:53:12 GMT</pubDate>
            <atom:updated>2022-01-19T21:15:50.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>GIT — Minimum commands to work like professional — Part 2</h3><p>In this article, we are going to see how to use Git effectively with minimum commands and with deep understanding of each one of them. Though it is a continuation of PART 1, I have managed to write most of the technical explanations and plumbing commands in that. So, the people who hate technical contents, please breath a sigh of relief. In PART 2, I am going to talk only from the GIT’s usage perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ShQYq8nhoTkISCdU" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sharing PART 1 link, in case if you are interested:</p><p><a href="https://faun.pub/git-basic-building-blocks-part-1-25be4cd4c87a">GIT — Basic building blocks — Part 1</a></p><h3>Points to remember</h3><p>If you haven’t read or understood PART 1, it is really fine. Just remember that:</p><ul><li><em>Git creates a </em><strong><em>hidden directory called “.git”</em></strong><em> for your repository and stores everything to track versions.</em></li><li><em>Git stores the revisions and file contents as DAG.</em></li><li><strong><em>Branch</em></strong><em> is nothing but a index/reference pointer in a DAG (Directed Acyclic Graph).</em></li><li><strong><em>master</em></strong><em> (You can rename it as “</em><strong><em>main</em></strong><em>”, “</em><strong><em>development</em></strong><em>” whatever) is the special reference pointer to git’s first branch .</em></li><li><strong><em>HEAD</em></strong><em> is a “movable” reference to a reference (Most times associated to master reference until switched).</em></li></ul><h3>How to use Git?</h3><p>To use GIT effectively, I would recommend to use it through <strong><em>command line </em></strong>for daily activities.<strong><em> </em></strong>There are many GUI wrappers available. Those abstractions would hinder your learning, sometimes confuse you and ultimately you would end up learning that wrapper and not Git actually.</p><p>Definitely nothing wrong in installing GUI wrappers like Github Desktop, Tortoise Git etc. In fact, I recommend you to install if possible. But use them only for “few” activities like comparing files, visualizing logs revisions and to some extend resolve complex conflicts too.</p><h3>The types of GIT users</h3><p>There are 2 kind of developers who use Git or any version control system.</p><ul><li>Type 1 — A developer would develops some application(s) on his own, maintain it in Git and later allow it to be pulled by multiple people who can either contribute or just consume it.</li><li>Type 2 — A develops who works in an organization. It maintains product’s source code in Git. As a developer, he just pulls it and develops on top of it.</li></ul><p>The workflow of Type 1 user is different from Type 2. So let me segregate my commands based on the type of users.</p><h3>Bare minimum GIT commands to work like PRO!</h3><p>Let me start with Type 1 user. Assume, you have a directory called “<em>GitTutorial_1</em>” and it is empty.</p><h3>1. git init</h3><p>After installing Git in your system, as a Type 1 user, you need to start with it. You need to mark your code base as Git repository. How would you do it?</p><pre>git init</pre><p>That’s the first ever command to learn. It creates a hidden directory called “.git” to track the file as I already explained. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*0XLN34U9GXrRF0SpBnJAwA.png" /></figure><p><strong><em>By the way, “git init” is not a useful command for Type 2 user</em>.</strong> Because his organisation would have already created a repository for him.</p><h3>2. git add</h3><p>After initializing, you would start adding/modifying your file(s). Let’s assume you create a file “firstFile.txt” file with text “Hello World”. After creating file, will it be automatically tracked in the git? No. It’s not the obvious choice that a file created\changed inside a git repository should be tracked always. If you need it to be tracked, you should inform git that these are files to be “considered” to be tracked for version. This is called <strong>staging</strong>. “<em>Git add</em>” does exactly that. <strong><em>It just marks file(s) to track and creates hash entry inside hidden “.git” directory</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*NBDQ4dWLGyWqwUWKE-ytoA.png" /></figure><p>You must be wondering about the “.” after “git add” command. It means, track “<strong><em>ALL the</em></strong><em> </em><strong><em>New and Modified</em></strong>” files inside the repository. Just remember below 4 variations.</p><pre>git add -u   // Track all Modified and Deleted files in repo<br>git add .    // Track all New and Modified files in repo<br>git add -A   // Track all New, Modified and Deleted files in repo<br>git add &lt;fileName&gt; // Track a particular new file</pre><blockquote><strong>“git add” tips:</strong></blockquote><p><em>As a beginner Type 2 user, I recommend to use </em><strong><em>“git add -u” followed by “git add &lt;fileName&gt;”</em></strong><em> for each new files. This way you can avoid committing unnecessary auto created files if any (*in case if you have not set to ignore using .gitignore file).</em></p><h3>3. git commit</h3><p>After marking your file(s) for tracking, you need to commit these changes as a <strong>version\revision</strong> to your local repository. A commit is a logical collection of files solving a particular problem. In our example, you wanted to say this world a “Hello”. So just creating a file with “Hello World” qualifies a commit.</p><p>By doing “git commit” you are technically creating new hash of commit index connecting those file hashes created by “git add”. <em>Thus, “.git” hidden directory creates with new edges and vertices in DAG of new hashes (only for changed files) and reference back unchanged blobs as I explained already.</em> You generally use commit command as below:</p><pre>git commit -m &quot;&lt;your message explaining commit&gt;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*eH_1p4INh40IFqK0IgVRxA.png" /></figure><h3>4. git branch</h3><p>This is the next command you need to know to understand the flow.</p><pre>git branch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*00RRfXgKnBe7Ar2oYAJrUA.png" /></figure><p>When executed, it will tell you which branch you are currently on. By default, git creates a branch called “<strong>master</strong>” once you commit. I will explain creating your own branches in a while.</p><h3>5. git remote</h3><p>With those 3 commands, you created version(s) and maintain it just in your local system. By now, Git is just a “<em>Content tracker</em>” and not even “<em>Version Control System</em>”. A version control system would be justified if used by two or more people. To do so, you need to publicly share your local computer storage. But, self hosting is unnecessary and make the things complicated. There are dedicated sites to do it and few famous ones are <strong>github</strong> and <strong>bitbucket</strong>. It is out of scope to deep dive on them and thus skipping it. After identifying the remote location, you need to mark your code in sync with the remote http address. Here is how you do it:</p><pre>git remote add &lt;name&gt; &lt;remote url&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*loQaTP9nKMi7EqTc3z4UeQ.png" /></figure><p><strong>Origin</strong> is the alias name of your remote url.</p><h3>6. git push</h3><p>After marking “remote” to external link, how would you push your version to the remote repository? “Git push” does that. The default name of your local repository is “master” which you want to push in with the same name. “Origin” is the alias of your remote repository. Here is the command to push it to remote server location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*sViW8kLVHcJFjkr_cg2unQ.png" /></figure><blockquote><strong>“git push” tips:</strong></blockquote><pre>// Usually, you never push to remote &quot;master&quot; directly.<br>// Moreover, when you have local branch with some name, git push would create remote branch with same name.<strong><br>git push origin JIRA-123</strong> //push it to a remote branch &quot;JIRA-123&quot;</pre><h4>Deviating workflow:</h4><p>Now let’s take a pause and worry about the Type 2 user. As a consumer of git repository, he don’t have to use “git init” and “git remote” because someone in his organization would have already initiated and linked and pushed to a remote github site.</p><h3>7. git clone</h3><p>Just consider, he wants to use the repository which we have created and pushed to a remote site. How can he start with it? “Git clone” is the first command to help him. He need to clone the product’s source code into his local system like this:</p><pre>git clone &lt;remote url&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*wlGCItQhKG84BF-Snk1XEQ.png" /></figure><h3>8. git branch -c &lt;new Branch&gt;</h3><p>We had seen how to view branches in point 3. Here, I will explain how to create your own branch.</p><p>I already hinted on “git push” tips. To push into a custom branch, you should create it first. But why you need a branch for yourself? Think about it.</p><ul><li>Though technically possible, if you allow multiple people to push into “master” directly, it will soon be a garbage without control.</li><li>Moreover, you need a logical name for your commits.</li></ul><p>That’s when the concept of “branch” is useful. Below is command to create a branch locally:</p><pre>git branch -c Idea1 // Creates a new branch Idea1</pre><p>Consider, you have an idea to change “Hello World” to “Hello Galaxy” in our example. You create a branch like above, then add and commit. <strong><em>All those adds and commits is in your local branch and not in the “master”</em></strong>. When you push, the changes would get into the remote site as your branch &lt;name&gt; and “master” would remain undisturbed. Later, product owners review the changes and merge to “master” in remote.</p><p>So 2 things you have done. You have created a branch locally and then while pushing, you created a branch in the remote site too.</p><blockquote><strong>“git branch” tips:</strong></blockquote><pre>git checkout -b JIRA-123 // To create branch and checkout to that.<br>git branch -c JIRA-123 // To create a branch.</pre><pre>git branch -D JIRA-123 // To delete a local branch<br>git push origin --delete JIRA-123 // To delete a remote branch</pre><h3>9. git pull</h3><p>After “git push”, your changes would get into the remote repository of yours. <em>**Out of scope: </em><strong><em>Github</em></strong><em> workflow has a mechanism of validating your branch as a “</em><strong><em>pull request (PR)</em></strong><em>” and “</em><strong><em>merging</em></strong><em>” it with master in the remote site itself.</em></p><p>After that step, any user having access to that public repository can pull and see the complete snapshot of your revision local to their system. That’s how we made git as “Version Control System”. We bring the entire set of revisions present in the public repository local to your system. The command is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*6mDObBvMrU3Bv5iYkpAapw.png" /></figure><p>That’s the logical end of basic commands to work with. Below is the workflow of any developer’s day in, day out.</p><h4>Type 1: Init →[add →commit →[remote]ᵒⁿᶜᵉ→push ←→pull]ᴺ ᵗᶦᵐᵉ</h4><h4>Type 2: Clone →[add →commit →push←→pull]ᴺ ᵗᶦᵐᵉ</h4><p>Below are few more commands which you must know:</p><h3>10. git merge</h3><p>This is very useful command to do merging locally, especially when you are working with multiple branches local to your system. In the below example, “master” and “A0001” can be evolved separately and soon they will go out of sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*EOa1lo4UH2QHTrlMTUmpaw.png" /></figure><pre>git merge &lt;custom Branch&gt;</pre><p>Until there are no conflicts, merging would be performed automatically when above command issued.<strong><em> Merging is a special commit with 2 or more parents.</em></strong> Otherwise, there is no difference between a normal commit and a merge.</p><h3>11. git switch/checkout</h3><p>When you create multiple branches local to your system, “git checkout” is the useful command to switch between branches and work. (*There is something called “<strong><em>git switch</em></strong>” which does the same, but I recommend to use “git checkout” as it is more powerful and “git switch” may be deprecated soon.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*QJmfoI1yJRJOQuocGLI-cQ.png" /></figure><h3>12. git status</h3><p>Last by not the least command. It may be possibly, the most frequently used git command by anyone. It tells the current status of your work space. What files are changed locally and what files are added etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*izCYEHtUmTcRex1SqZXOPg.png" /></figure><p>I think now you would have got the complete picture of Git. To any “public repository”, User A can bring in branch “A0001”, User B can bring in branch “B0001”, User C can bring in branch “C0001” etc., and merge it. Once you do a “git pull” in you local machine, you should have “A0001”, “B0001” and “C0001” all local to your system. Because, those would have been merged to “master” at some point of time. Thus Git a “<strong>Distributed Version Control System</strong>”</p><blockquote><strong>Honorary Mentions:</strong></blockquote><p><strong>Reset, rm, tag, log, diff, difftool, revert, fetch, rebase</strong> can be very handy and useful commands. You can search for it when required. For some commands, use it through GUI wrappers as they visualize them much better.</p><h3>What is not Git?</h3><p><strong>Fork </strong>and<strong> Pull Request (PR) commands, are not GIT commands. </strong>FYI, they are not even part of “Distributed Version Control System”. They are the commands and concepts of Github or any public hosting repository to do the commits gracefully and merge securely. It is out of scope for this article, but you MUST know them.</p><h3>Conclusion</h3><p>There are many other Git commands which are obviously useful. But <strong>add, commit, push, pull</strong> along with <strong>branch, checkout, merge, status </strong>is the staple diet for many of us. People are using it so mechanically that they do not even bother to understand how and why it works that way. If you know how it works, you don’t even bother to remember it. I hope I have justified about it in these 2 articles. That’s all from me. Adios!</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d63a0485759a" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/git-minimum-commands-to-work-like-professional-part-2-d63a0485759a">GIT — Minimum commands to work like professional — Part 2</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT — Basic building blocks — Part 1]]></title>
            <link>https://faun.pub/git-basic-building-blocks-part-1-25be4cd4c87a?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/25be4cd4c87a</guid>
            <category><![CDATA[sha-1]]></category>
            <category><![CDATA[git-internals]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control-system]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 08:10:57 GMT</pubDate>
            <atom:updated>2022-01-11T19:48:40.733Z</atom:updated>
            <content:encoded><![CDATA[<h3>GIT — Basic building blocks — Part 1</h3><p>At present Git is the most used “<strong>version control system</strong>” in the world, at the same time, a misunderstood and mechanically used tool for many too. There are hundreds of articles and videos about it, but not many talks about its building blocks. They would be overly articulating about the usage and commands. Even if you go through the official documentation, you can only get the hang of usage but not the internals. Internals are fun to know and it will boost your confidence while you use the product. So in PART 1, I explain the internals in simple terms as usual. Let me see if I can do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qX8R2e_GeKY6UvxXHxcsOA.jpeg" /></figure><h3><strong>GIT is Distributed Version Control System — What that means?</strong></h3><p>The creator of GIT is none other than <strong>Linus Torvalds</strong>. Hope you know his first product, the “<strong><em>LINUX Kernel</em></strong>” which is ruling the world. What else do you expect out of him? Just one more product to rule the world.</p><p>And first thing first! Git is just a “<strong><em>stupid content tracking tool</em></strong>” as expressed by the creator himself. How it was made as a “<strong><em>Distributed Version Control System</em></strong>” is sheer brilliance. It means, it does the following:</p><ol><li><em>It tracks the different versions of the evolution of a file.</em></li><li><em>If needed, it allows us to get back to a particular version quickly.</em></li><li><em>Tracking back and forth is not just for a single file but for the entire repository as a revision.(*After all, the entire repository is just Trees and blobs)</em>.</li><li><em>You don’t have to connect to a server for switching between versions/revisions.</em></li><li><em>All the above-mentioned works in a distributed way i.e., everything is brought in your local system. The server contents are a mere copy of what you have locally.</em></li></ol><blockquote><strong>Centralized Vs Distributed</strong></blockquote><p>In a <strong>centralized repository</strong>, multiple versions of files is maintained in a central server. When people sync for the recent changes at some point, it downloads the very recent snapshot from the server. Later, if you want to go to any other previous version, you can fetch that from Central Server and replace it locally with the one you have. That means, at any point in time, just only one snapshot is present in your local machine.</p><p><strong><em>In contrast, once you clone/pull, Git stores everything in its entirety in your local storage. </em></strong>Let’s assume you have 20 released versions of your repository, Git stores all those 20 snapshots in your local system and you can go back and forth without connecting to any server.<strong> </strong>I know you might be asking me like — “<em>Wait! Let’s say my repo size is 5 GB and it stores 20 versions of it in my local repository, so it sweeps off 5*20 = 100 GB of my disc space?</em>”. Actually no! That’s the beauty of Git. How Git stores and visualizes files really matters and that unique mechanism gives the power of distributed nature of it.</p><blockquote><strong>Hash &amp; DAG — Keep these in mind.</strong></blockquote><p>Before getting into the Git object model, you must know the following about Hash:</p><ol><li><em>Hashing is different from encryption and it is one way i.e, you cannot get the hashed content back with the help of hash.</em></li><li><em>Hashing is a mechanism of producing “digest” for a given stream of characters.</em></li><li><em>A digest is a unique standard size of bits.</em></li><li><em>SHA-1 used in GIT is one of the famous Hashing mechanisms, which produces 160 bits of “digest” for any stream of characters as input.</em></li><li><em>A “digest” is usually represented in Hexadecimal values (4 bits), thus an SHA-1 digest would look like 40 (160/4) hexadecimal characters.</em></li><li><em>There is no size or word limitation on the input stream of characters.</em></li><li><em>A trillion characters content or a single character content, both result in a Hash of the same size i.e., 40 Hex Characters.</em></li><li><em>Hash keys produced by SHA-1 are unique and it is humanly impossible to collide for 2 different contents. Let’s not debate on that.</em></li></ol><p><em>Another concept to remember is DAG. DAG (“Directed Acyclic Graph”) is one type of graph representation without cycles. Tracking evolution is one of its use cases.</em></p><blockquote><strong>Git’s Object Model — Quick glance</strong></blockquote><p>On your git repository, you will obviously see the current working snapshot of your files. The rest all files of the multiple snapshots of your repository would be consolidated and represented in a hidden directory called “<strong>.git</strong>”.</p><p>Let me give a very quick overview of “.git&quot; storage structure straight away.</p><ul><li><em>Each Unique file (I mean the file contents) would be hash computed by Git.</em></li><li><em>If 2 or more files have “ditto” the same contents in your repository, then only one hash is computed.</em></li><li><em>The hash “digest” is the file name in “.git” and actual file contents will be compressed inside that file.</em></li><li><em>Every file of your repository is constructed like above when “added” to the git.</em></li><li><em>When you “commit” those changes (Let’s say C1), it will create a new commit index using its contents (commit text+username+timestamp+etc) as a new special hash object. Thus, it MUST be unique.</em></li><li><em>This special hash object (commit hash) will be connected to all those file content hashes like a DAG.</em></li><li><em>Later, whenever a file is changed and “added”, GIT creates a new hash file “only” for that file object.</em></li><li><em>When “committed” again (Let’s say C2), it will create a committed index connecting to that changed file. For the rest of the file objects, it connects them using a pointer to that sub-part of DAG.</em></li><li><em>Git visualizes the whole repository’s file system in its own style and stores them as commits, blobs (file contents), and trees with connections.</em></li></ul><p>All those mentioned are consolidated in that hidden <strong>“.git”</strong> directory present in your repository as I mentioned. That’s it! That’s the whole product. As I promised, I will not go further and this level of understanding is good enough to work with the product.</p><blockquote><strong>Some important “Reference Pointers” of GIT</strong></blockquote><p>Now we learned, if we just track the “commit” index, we can easily reconstruct a sub-tree of your DAG and that is your revision. How would you track it? It is again simple! Just with reference pointers. A reference pointer tracking a committed index is called “<strong>branch</strong>”. You can create as many branches as you can like “JIRA-123”, “stupidIdea”, “RTC-567” etc.</p><p>Irrespective of you creating a reference pointer, 2 reference pointers that you must know is <strong>HEAD &amp; master</strong>. You are free to rename “<strong>master</strong>” as “<strong>main</strong>”, “<strong>development</strong>”, “<strong>virgin</strong>” or whatever. But “HEAD” remains “HEAD”.</p><p><strong>master</strong> — It is a reference to the latest commit in the repository. This is also the first branch of a repository created by the git itself. Thus, it keeps tracking the latest snapshot in the repository.</p><p><strong>HEAD —</strong> This is a “movable” <strong>reference pointer to a reference pointer</strong>. Mostly, it would be referencing “master” branch until switched. When “switch/checkout” is called, it will reference that particular branch.</p><p>In the below diagram, I have abstracted commit as single entity (it will be pointing to multiple blobs and trees internally) to illustrate how master and HEAD moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDfbRJtzs7MqVAWXZydVIA.png" /><figcaption>Fig 1: Illustration on How Master and Head moves</figcaption></figure><p>Just by using this simple idea, you can track the entire versions of your GIT repository.</p><blockquote><strong>Some GIT plumbing command examples</strong></blockquote><p>Actually, there is no need for you to know the plumbing commands. They are just fun to dig and re-verify what I spoke about just now. I am giving it here, feel free to omit this section.</p><ol><li><strong><em>git hash-object</em></strong></li></ol><p>It produces SHA-1 hash for a given text. The same is used by git internally. You can’t directly use this command, but can pipe it through the “echo” command as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*wjGL0U2uxlCoXPe9m86o-Q.png" /></figure><p>The “objects” folder of git will find a new entry. git creates the first 2 “hex” as a folder name. The remaining 38 “hex” would be the file name. It is for easy indexing. It will appear as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*3qc7pU_dms194l7dTkzauA.png" /></figure><p><strong><em>2. git cat-file</em></strong></p><p>If you open that file in a notepad, the content would be compressed. Don’t worry, you can unzip it with git cat-file as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*2xEExfuwzfZ7_40URew4FA.png" /></figure><h3>Conclusion</h3><p>Now I believe you have understood the basic building blocks of Git. It is nothing but hash-named blobs, trees, and commits connected as DAG. It had reference pointers at multiple places to reconstruct a snapshot. Thus, Git visualizes the file system in its own way to reconstruct it quickly. This magic happens just locally in a distributed way. That’s pretty much about this article. There is PART 2 cooking and it is on the way. In that, I promise, I will talk only from the user perspective and you can use Git confidently thereon. Catch you, until then C’ya!</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25be4cd4c87a" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/git-basic-building-blocks-part-1-25be4cd4c87a">GIT — Basic building blocks — Part 1</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few modern C++ syntax you must adapt — PART II]]></title>
            <link>https://medium.com/@daloukalai/a-few-modern-c-syntax-you-must-adapt-part-ii-3bc840450667?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bc840450667</guid>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[rvalue]]></category>
            <category><![CDATA[reference]]></category>
            <category><![CDATA[move-semantics]]></category>
            <category><![CDATA[perfect-forwarding]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 17:23:24 GMT</pubDate>
            <atom:updated>2021-12-09T06:57:13.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>A few modern C++ syntax you must adapt — PART II</h3><p>As I already promised in PART I , there is a lot to discuss than what I have introduced to you in that article. PART 1 was mostly on the improvisations of your existing C++ coding practices. In this part, I will introduce few newer concepts which you must adapt along with it. By the way, people who have not visited that article, have a look there and get back.</p><p><a href="https://medium.com/@daloukalai/a-few-modern-c-syntax-you-must-adapt-48fbd5996743">A few modern C++ syntax you must adapt!</a></p><blockquote><strong>1. R-value Reference</strong></blockquote><p>Before typing anything, I reckon that “R-value Reference” alone will take the entire PART 2. With that disclaimer, come on! let’s roll.</p><p><strong>R-value reference</strong> is one of the important addition of C++11. But, before explaining about “<strong><em>R-value Reference</em></strong>” and it’s syntax, you must know what is “<strong><em>R-value</em></strong>” at first place. Historically, the name “<em>R-value</em>” and “<em>L-value</em>” comes from “<em>Right side value</em>” and “<em>Left side value</em>” in a expression respectively. For example:</p><pre>int x = 10;</pre><p>Here ‘x’ is l-value and 10 is r-value. So simple, right? Though in this example what I said is correct, it isn’t that simple in C++11. My grotesque definition goes like, <strong><em>anything which does not occupy an identifiable memory address at a given point of time in an expression is a R-value</em></strong>. In contrast, <strong><em>anything that occupies an identifiable memory address in an expression is a L-value</em></strong><em>. </em>When I say this, R-value is <strong><em>mostly</em></strong> suitable in the right side of an expression and thus the name R-value. Example:</p><pre>int x = 10; // 10 is Rvalue<br>int y = x+5; // (x+5) is Rvalue <br>Base b = Base(); // Base() is Rvalue<br>int sum = add(4,5); // add(4,5) is Rvalue</pre><p>As you see there, mostly constants, arithmetic expressions, constructors and function calls would qualify as R-value. <strong><em>One very important point is that expressions are not necessarily present in a single line as above. It can be through function calls.</em></strong> PLEASE KEEP THAT IN MIND. For example:</p><pre>// Pass by Value function<br>void func(int x)<br>{ <br>    cout &lt;&lt; x &lt;&lt; endl;<br>}</pre><pre>// calling that function by passing a sum function<br>func(sum(4,5)); // there&#39;s inherent expression &quot;int x = sum(4,5)&quot;</pre><blockquote><strong>Pass-by-Value and Pass-by-Reference</strong></blockquote><p>When you do such indirect inherent function call expressions, you need to know about another concept called <em>pass by value</em> and <em>pass by reference</em>. In <em>pass by value</em> assignment syntax, you can assign both L-value and R-value (<em>In the above example, you passed an R-value</em>). There is no distinction. But when you <em>pass by reference</em>, it must be L-value (* Exception: There is a <strong><em>const</em></strong> <strong><em>reference</em></strong> hack, which fakes like you can pass R-value, but it is just an illusion. I will explain later.) . So, the “<strong>&amp;</strong>” you call it as <strong><em>reference symbol </em></strong>in general, is not just <strong><em>reference symbol. </em></strong>It actually is “<strong><em>L-value reference symbol”. </em></strong>Which means, it would reference only the L-value in an expression and NOT R-value.<strong><em> </em></strong>For example:</p><pre>void func(int <strong>&amp;</strong>x)<br>{<br>   cout &lt;&lt; x &lt;&lt; endl;<br>}</pre><pre>// calling that function<br>func(sum(4,5)); // int &amp;x = sum(4,5) =&gt; This will result in error<br>func(5); // int &amp;x = 5 =&gt;This is again error<br>int i = 10;<br>func(i); // int &amp;x = i =&gt; L-value assigned and thus it will work.</pre><p>Now, how can you reference an R-value? Until C++11, you cannot. From C++11, you can reference an R-value with “<strong>&amp;&amp;</strong>”. Example:</p><pre>void func(int <strong>&amp;&amp;</strong>x)<br>{<br>   cout &lt;&lt; x &lt;&lt; endl;<br>}</pre><pre>// calling that function<br>func(sum(4,5)); // int &amp;&amp;x = sum(4,5) =&gt; This will work<br>func(5); // int &amp;&amp;x = 5 =&gt;This will work<br>int i = 10;<br>func(i); // int &amp;&amp;x = i =&gt; This is L-value and will not work.</pre><p>Hope you got the concept and it is so easy. But I can hear you asking me, “<em>I know L-value reference solves unnecessary copy of objects. Why the heck I need a R-value reference and what problem it solves?</em>”. Ah, did I get hear you correct? So in the normal function calls like above, I don’t think it is solving any big problem. But in real sense, it serves for 2 purposes viz., <strong><em>Move Semantics</em></strong> and <strong><em>Perfect Forwarding</em></strong>. We can see them in detail.</p><blockquote><strong>1.a Move Semantics</strong></blockquote><p>Before going to move semantics, you need to know what is <strong><em>copy constructor</em></strong>. Copy constructor is the one which recreates an object “<em>as is</em>” in all sense. Which means, if the copied object involves with heap memory for any of its member, then it is the duty of copy constructor to do a <strong><em>deep copy</em></strong> for that member. Copy constructors are auto generated when not defined. But if you leave the job to auto generated ones, it will not achieve the “<strong><em>Copy Semantics</em></strong>” as I explained. So we overload our copy constructors, especially when we involved pointers members in our class. It would make sure the sanity of “<strong><em>Copy Semantics</em></strong>” is maintained.</p><p>Now consider a very big object. Every time a copy constructor is called, a very big object is created. If you really need it to be copied and created intentionally, then it is fine. But sometimes you would call copy constructors on transient objects and it would lead to a bad performance problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e14a0e895a454e251ae38e2e0a5b68e/href">https://medium.com/media/4e14a0e895a454e251ae38e2e0a5b68e/href</a></iframe><p>Consider the above example. I illustrated 3 ways of consuming an already created object. First way, an object was created in <em>line 43</em> and you consume it by calling a copy constructor in<em> line 48</em>. Thus, you perform <strong><em>one copy constructor</em></strong>. It is somewhat acceptable. You would avoid this completely, by passing reference as explained in <em>line 53 (Here no constructor is called and hence this is the best. But you need reference overloaded function for every method)</em>. However, the call in <em>line 58</em> is unacceptable. Because you first create a temporary object and then you call a costly copy constructor. So the object construction happens twice unintentionally and unnecessarily. Had we defined a “<strong><em>Move constructor</em></strong>”, this would be avoided.</p><p>“<strong><em>Move Constructor</em></strong>” is a new type of constructor with C++11. It is not possible if we do not have “<strong><em>R-value Reference</em></strong>”. Basically, instead of deep copying the values like copy constructor, you literally move the entire copied object to the new object. After moving, the copied object should hold nothing and point to NULL. This is called “<strong><em>Move Semantics</em></strong>”. Have a look on how we achieved it:</p><pre>// Define this move constructor after line 20 in the above program<br>// You can evolve from copy constructor as below<br>// Point 1: drop const (because you modify moved object to NULL)<br>// Point 2: Use &amp;&amp; in the constructor <br>Image(Image <strong>&amp;&amp;</strong>b)<br>{<br>  size = b.size;<br>  raw = b.raw; // Point 3: Shallow copy the members<br>  b.raw = nullptr; // Point 4: nullify the copied object<br>}</pre><p>So basically you defined a constructor with “<strong><em>R-value reference</em></strong>”, that’s your <strong><em>move constructor</em></strong>. Hereafter, if you call a constructor to assign an object which created on-the-fly (basically any R-value), you would call “<em>Move Constructor</em>” (provided it is defined). If not defined, a 2 step object creation would happen as explained before. This move call is cheap and very useful for big objects. It drastically improves the performance of the code.</p><p>So it is a good practice now to define “<strong>Move constructors</strong>” and “<strong>Move Assignment Operators</strong>” along with “<strong>Copy constructors</strong>” and “<strong>Copy Assignment operators</strong>” for user defined classes in C++11. This will take care of “<strong><em>Move Semantics</em></strong>” (both intentionally and unintentionally). Good News! All STL classes are overloading with “<strong><em>Move constructors</em></strong>”and “<strong><em>Move Assignment Operators</em></strong>” inherently in C++11. You would see some performance improvement when STL is used in C++11 without doing anything from our side.</p><blockquote><strong>1.b Perfect Forwarding</strong></blockquote><p>Ok, let’s move on to the next usage of “<strong><em>R-value reference</em></strong>” which is “<strong><em>Perfect Forwarding</em></strong>”. So far in the above examples, you had seen R-value reference object creation which automatically calling “move constructor”. How would you call it intentionally? I mean, in that above example, how would you call move constructor instead of copy constructor in the <em>line 48</em>? Is that possible? Yes, you should use <strong><em>std::move()</em></strong> which mandates move constructor even on the L-value like below:</p><pre>consume(<strong>std::move</strong>(masterCopy)); // This mandates move constructor</pre><p>Sometimes, it is mandatory to move a L-value from one function space to other. You convert it as R-value and move it to other function’s space. Thus, <strong>std::move converts argument into R-value</strong>.</p><p>There is something called <strong>std::forward. It converts argument into “T&amp;&amp;”</strong>. By looking at this explanation, many people have a misconception that <strong>std::forward</strong> also does exactly the same, because they know “&amp;&amp;” represents R-value. Actually they are wrong! “<strong>&amp;&amp;</strong>” is also called as <strong>Universal Reference</strong> when used alongside Templates (Applies only to Function Templates). So, <strong>T&amp;&amp; is called Universal reference</strong>.</p><p><strong><em>What is Universal Reference and how it is achieved?</em></strong></p><p><strong>Universal reference</strong> (<strong>T&amp;&amp;</strong>) is something which makes sure L-value can be passed as L-value and R-value can be passed as R-value. Even const, non-const and every sanity of the passed in argument would be maintained. It is achieved by a new concept in C++11 called “<strong>Reference Collapsing Mechanism</strong>”. Just remember the below rule table and I will quickly explain it. You can remember the rule like “<strong>single ampersand (&amp;) is infectious”</strong>. If present, it will always result in single ampersand(T&amp;). Only if both are double ampersand (&amp;&amp;), then it results in &amp;&amp;.</p><pre>T&amp;  + &amp;  = T&amp;<br>T&amp;  + &amp;&amp; = T&amp;<br>T&amp;&amp; + &amp;  = T&amp;<br>T&amp;&amp; + &amp;&amp; = T&amp;&amp;</pre><p>The above collapsing would be done ONLY by the compiler. Basically when you write a template function with &amp;&amp;, it will automatically infer to the passed in type as reference. I can illustrate with a below example:</p><pre>template&lt;typename T&gt;<br>void myFn(T&amp;&amp; arg)<br>{<br>// do something<br>}</pre><pre>...<br>// call  from main<br>myFn(6); // Its R-value for T&amp;&amp;, So T&amp;&amp; + &amp;&amp; = T&amp;&amp;<br>myFn(i); // Its L-value for T&amp;&amp;, So T&amp;&amp; + &amp; = T&amp;</pre><p>Now let’s get back to the old example. Consider a similar template function like above is with your code and you call “<em>consume()</em>” function using that i.e., you replaced the <em>line 48 and line 58</em> of your main function to use that. The call would look like below:</p><pre>template &lt;typename T&gt;<br>void forwardFn(T arg)<br>{ <br>   consume(arg);<br>}</pre><pre>...<br>forwardFn(masterCopy); // line 48<br>...</pre><pre>...<br>forwardFn(imageFactory()); // line 58</pre><p>Now, the real problem. Here in <em>line 48</em>, you passed L-value and in <em>line 58</em> you passed R-value. How would you maintain that sanity? Simple! First, you need to change the template function to T&amp;&amp;. Second, you forward the argument using std::forward. You remember what I said about std::forward? It converts arguments to T&amp;&amp;. So, the function can be re-written as below:</p><pre>template &lt;typename T&gt;<br>void forwardFn(T<strong>&amp;&amp;</strong> arg) // receive as T&amp;&amp;<br>{ <br>   consume(<strong>std::forward&lt;T&gt;</strong>(arg)); // then forward (converts T to T&amp;&amp; internally)<br>}</pre><p>Thus, it make sure it receives T&amp;&amp; and it forwards T&amp;&amp;, such that L-value is passed as as L-value and R-value is passed as R-value in an expression. This is called “<strong><em>Perfect Forwarding</em></strong>”.</p><blockquote><strong>Conclusion</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b62a2q8EvNOe2wkr7MV_1w.jpeg" /></figure><p><strong><em>R-value reference</em></strong> and its usages like “<strong><em>Move Semantics</em></strong>” and “<strong><em>Perfect Forwarding</em></strong>” are one of the confusing concepts of C++. But Einstein said, “<strong><em>If you can’t explain</em></strong><em> </em><strong><em>it simply, you don’t understand it well enough</em>”. </strong>On that note, I believe I have explained it in simpler terms. Shout out if I missed clarity, I will correct it. Also, I will meet you soon in the PART 3 of it. There is more to cover and more to learn. Until then C’ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc840450667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few modern C++ syntax you must adapt!]]></title>
            <link>https://medium.com/@daloukalai/a-few-modern-c-syntax-you-must-adapt-48fbd5996743?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/48fbd5996743</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[cpp17]]></category>
            <category><![CDATA[cpp14]]></category>
            <category><![CDATA[cpp11]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 17:29:01 GMT</pubDate>
            <atom:updated>2021-11-19T17:29:01.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Being a old school programmer who started C++ programming a little more than a decade and half ago, I used to feel that the <strong><em>modern C++</em></strong> syntax are really vexing and killing the fun. It took a lot of time for me to upgrade my compiler and my lethargic mind to C++11. But after I started using new syntax for couple of years , it was really addictive and made the life easy. I am going to discuss few of them here, try to use it and it will be fun. OK, let’s quickly jump into the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oexl6jDrUWbbrBUi" /><figcaption>Photo by <a href="https://unsplash.com/@clarktibbs?utm_source=medium&amp;utm_medium=referral">Clark Tibbs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>1. Auto and iterators</strong></blockquote><p>This is the first and foremost thing that comes to my mind, which made the thing easy. I really thank this syntax, not just for “<em>auto</em>” keyword. I do not have the practice of defining my <strong><em>int/double/float</em></strong> variables as <strong><em>auto</em></strong>. Because when I declare something, mostly I know the purpose and scope of it too. But when you use it alongside “<strong><em>Iterator</em></strong>” it is very powerful and you can avoid a vexing syntax in C++. Consider the following simple example of std::vector and looping it:</p><pre>vector&lt;string&gt; students;<br>for(<strong>vector&lt;int&gt;::iterator</strong> it=students.begin(); it!=students.end(); ++it) {<br>    cout &lt;&lt; &quot;print details&quot; &lt;&lt; endl;<br>}</pre><p>Instead of it, you can write something like below:</p><pre>vector&lt;string&gt; students; <br>for(<strong>auto</strong> it= students.begin(); it!= students.end(); it++){<br>    cout &lt;&lt; &quot;Print details&quot; &lt;&lt; endl;<br>}</pre><blockquote><strong>2. For…Each syntax</strong></blockquote><p>On top of it, if you use For.. Each syntax, it will make life so easy to create a loop. I have started using this syntax for almost all STL iterations. You can see how nicely we evolved.</p><pre>vector&lt;string&gt; students;<br><strong>for(auto v:students)</strong>{<br>    cout &lt;&lt; &quot;print details&quot; &lt;&lt; endl;<br>}</pre><blockquote><strong>3. Initialization List</strong></blockquote><p>In those old days, another big problem is the initialization of STLs. It is really worrisome when you want to statically initialize a list/vector etc., through old syntax. You need to call some STL method each time as below:</p><pre>vector&lt;string&gt;students;<br>students.push_back(&quot;Lucy&quot;);<br>students.push_back(&quot;Manny&quot;);<br>students.push_back(&quot;Mark&quot;);</pre><p>But nowadays you can initialize them like an array. This was not possible in old C++ compiler.</p><pre>vector&lt;string&gt; students = {&quot;Lucy&quot;, &quot;Manny&quot;, &quot;Mark&quot;};</pre><blockquote><strong>4. Shared Pointers</strong></blockquote><p>Actually, <strong>Raw pointers</strong> concept is the boon and curse of C++. The biggest nightmare you get when you start designing some application with C\C++ is about the M<strong><em>emory leaks </em></strong><em>and</em><strong><em> Dangling pointers</em></strong>. In fact, while designing an application, you think, then drop the idea of C++, go safe way and code it in Java, right? Don’t do that for this sake at least. Dare to do programming in C++ and “<strong><em>Smart Pointers</em></strong>” are there to help you. Smart pointers are nothing but taking care of de-allocation of heap memory automatically, which in turn prevents memory leaks and dangling pointers.</p><p>The “<strong><em>Smart pointer</em></strong>” concept is achieved by 3 variants of implementation in C++ viz., “<strong><em>Shared Pointers</em></strong>”, “<strong><em>Weak Pointers</em></strong>” and “<strong><em>Unique Pointers</em></strong>” (<strong><em>Auto_ptr </em></strong>a close buddy to<strong><em> Unique_ptr </em></strong>is deprecated; that’s another story) in C++11. If you are a newbie, don’t worry much about “<strong><em>Weak Pointers</em></strong>” and “<strong><em>Unique Pointers</em></strong>” at present. <em>“</em><strong><em>Shared Pointers</em></strong><em>” are the closest representation of you raw pointers usage in your daily programming</em> (<em>Disclaimer: This statement is for ease</em>). I assume, 1) You usually assign a pointer to point to some memory, 2) reassign a pointer to other memory location later and 3) two or more pointers can point to same memory location. Most people use raw pointers like that. In such case, you can directly feed in “<em>Shared Pointers</em>” in your usage. Shared pointers adapts “<strong><em>reference counting</em></strong>” mechanism to keep track and delete. Thus multiple pointers can point to same memory location. Below are few use cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb1a9a244e02ecc2b19db58149246686/href">https://medium.com/media/cb1a9a244e02ecc2b19db58149246686/href</a></iframe><blockquote><strong>5. Standard threads</strong></blockquote><p>If you have worked in older code bases, you might have seen <strong>#if _WIN32</strong> and <strong>#if _unix </strong>etc., remember? Basically, you would write a part of code to work specific to <em>Windows</em> and part of code specific to <em>Unix</em> for<em> </em><strong><em>Cross Platform</em></strong> compliance. Especially when you are using threads, you have no choice and you had to do this. Because, threads in Windows OS (WIN32) is completely different from Unix OS (POSIX) threads.</p><p>In order to avoid this, most people use BOOST library threads, which had the internal wrapper to handle these cross platform complexities. Though it is free and open source, a 3rd party library is always a 3rd party library. We have our own challenges to use it in our product.</p><p>The point I am making is, C++ compiler, do not have generic thread concepts like BOOST until C++11. With the latest C++, you can start using standard library’s <strong><em>std::thread</em></strong> instead of <strong><em>boost::thread</em></strong>. And the good news, the syntax remains exactly same (Thanks to Anthony Williams). You just need to replace the <em>namespace</em>. You would definitely enjoy using <em>std::thread</em> and it is so simple to use. Also it is a must learn. This way of threading is most used in modern era of coding than WIN32 or POSIX threads. I stop at here about threads with the following simple example, because its a big topic and we can discuss in forthcoming articles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b04d456670d81e0910203f932d458440/href">https://medium.com/media/b04d456670d81e0910203f932d458440/href</a></iframe><blockquote><strong>6. Override and Final</strong></blockquote><p>For a longtime, these keywords were very specific to Java and to many other modern programming languages. Now, it is part of C++ too. You must be wondering what gone wrong with “<strong><em>virtual</em></strong>” keyword in C++. Don’t worry, nothing changed. “<em>Virtual</em>” is still the king and it is more than enough to exhibit “<strong><em>Run time Polymorphism</em></strong>”. The keyword “<strong><em>override</em></strong>” is a reassertion in the derived classes to convey strongly that the method is indeed a polymorphic function.</p><p>You may think this reassertion is cosmetic, but sometimes it would avoid unintended programming mistakes like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e5614cf9a3230eac63588008f1ac9d8/href">https://medium.com/media/2e5614cf9a3230eac63588008f1ac9d8/href</a></iframe><p>Surprise!! The above code would call base class function and print “<em>Base value 5</em>” while you expect polymorphism. You might be breaking your head why polymorphism is not working. Because, you missed polymorphism by forgetting “<strong><em>const</em></strong>” in the <strong><em>line 12</em></strong>. It is a different function signature altogether when compared to <strong><em>line 6</em></strong> and thus you have 2 different functions.</p><p>If you had used “<strong><em>void func1(int a) override {…}</em></strong>” in line 12, this would have caught at the compile time itself. That’s the real use of it I can see. So my advice is to mark “override” whenever you override in derived class. It is useful both cosmetically and for early catching of errors.</p><p>Next is the keyword “<strong>final</strong>”. As the name suggests, it will make a class or a virtual function not to be derived any more. This is typically useful when you make some design decisions that a particular class or function cannot be derived anymore.</p><pre>//usage 1<br>class ConcreteClass <strong>final</strong> { };<br>class Derived : ConcreteClass { }; // NOT ALLOWED</pre><pre>//usage 2<br>struct Base { <br>    virtual void fn() <strong>final</strong>; <br>};</pre><pre>struct Derived2 : Base {<br>    void fn(); // NOT ALLOWED<br>};</pre><blockquote><strong>7. = Delete</strong></blockquote><p>Like any other interviewer, I used to ask a standard interview question about “<strong><em>Private constructors</em></strong>”, a technique of <strong>restricted Object creation.</strong> Private constructors are the only way to restrict a specific form of object construction from outside world. But I stopped asking it now. Because, while I was expect “<strong><em>private</em></strong>” concept, people surprise me with modern “= <strong><em>delete</em></strong>” syntax. It does exactly same. Whenever you do not want any specific function format not to be exposed, you can mark it as =delete.</p><pre>class X {<br>    // ...<br>   X&amp; operator=(const X&amp;) = delete;  // Disallow assignment operator<br>   X(const X&amp;) = delete; // Disallow copy constructor<br>};</pre><blockquote><strong>A Definite miss in this article!</strong></blockquote><p>I should have explained about <strong><em>Weak Pointers</em>,<em> Unique Pointers</em>, <em>R-value, Move semantics, Perfect forwarding, Regular Expressions, Tuples, Lambdas, Future and Promise</em></strong> etc, as they were equally important. But, I am signing off with the confident that you would explore them by yourself until I finish writing my next article on those concepts. Thanks and we will meet in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48fbd5996743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POLYMORPHISM —What you would need to know?]]></title>
            <link>https://medium.com/@daloukalai/polymorphism-what-you-would-need-to-know-45edb800e338?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/45edb800e338</guid>
            <category><![CDATA[tmp]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[crpt]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 12:42:11 GMT</pubDate>
            <atom:updated>2021-10-29T07:53:43.833Z</atom:updated>
            <content:encoded><![CDATA[<p>When I ask about “Polymorphism” in interviews, almost everyone knows about it. But if I get into the depth of it, many choke. It is basically because there are some concepts that you’d understand only if you had practiced or at least read about it in depth. Let’s say, if I ask what is “<em>Static Polymorphism</em>”, many people will confuse it with “<em>Compile-time polymorphism</em>” and get into the details of Function/Operator Overloading. So, let’s try to learn it from the basics to the point where this article will not reach more than 5 mins of read. I hate big articles. <em>C’est parti!</em></p><blockquote><strong>On Boarding Mr. Poly</strong></blockquote><p>Let’s first discuss the basics. Polymorphism is one of the important aspects of Object Oriented Programming (OOPs). There are multiple definitions for it. Basically, people say, if something (object/function/operator) is exhibiting different behavior at different instances of time, it is called Polymorphism. This definition is partially true and holds good only if the polymorphism is a “<em>Compile time polymorphism</em>”.</p><p>As the name suggests, the polymorphism that would get detected by the “<em>compiler</em>” during the compile time itself is called “<em>Compile time polymorphism</em>”. Function Overloading and Operator Overloading (even Templates too) are the examples of compile-time polymorphism. They are very straight forward.</p><p>Let say we have an “<em>Add()</em>” function which would add two “<em>Integers</em>”. We can have the same function name to add two “<em>Double</em>” also. Basically, you write 2 functions with same name with different parameters.</p><pre>int add(int a, int b)<br>{<br>    return  (a+b);<br>}</pre><pre>double add(double a, double b)<br>{<br>    return  (a+b);<br>}</pre><pre>void main()<br>{<br>    add(5,6);<br>    add(2.35, 5.63);<br>}</pre><p>From the main function, the function it calls is decided well during the “<em>Compile-time</em>” itself. Hence compile time polymorphism.</p><p>I hear “Silly-Willy” is asking me, “Why not to name ‘AddInt()’ and ‘AddDouble()’ as their function names?”. Well, you can and completely avoid this unwanted polymorphism (If at all you feel that way). But “Add()” as a name, brings in more generic terminology to that function.</p><blockquote><strong>I am the real Mr.Poly!</strong></blockquote><p>The next one is “<em>Run time polymorphism</em>”. As the name suggests, the polymorphism will not be realized until the execution of the program. I mean, the underlying conversion of your source code into Intermediate representation by your compiler (in Java, we call Byte Code) does not have any trace of which function would get called until it is called in runtime. So this version of Mr.Poly is always exciting and bring the real flavor of Object Oriented Programming (OOP). This version always shouts out saying “<em>I am the real Poly!</em>”, as it will not be realized until the runtime.</p><p>I would like to slightly change the definition of polymorphism when it is “Runtime”. I can say here, <strong><em>“The object exhibits different behavior at different levels of its abstraction”</em></strong>. The moment I say “<strong><em>levels</em></strong>”, inheritance comes into play. In other words, inheritance plays the important role is “Run time Polymorphism”.</p><p>Take a classic example, Vehicle. Be it “Car”, “Motor-Bike”, “Bi-cycle” etc, anything can be called as a vehicle. Now, let’s assume there is an instructor stays far away and command to all the vehicle owners. As an instructor (otherwise the client code), he say someone to <strong><em>start the vehicle. </em></strong>The mechanism/steps to start the vehicle is purely depends on which vehicle he possess. From the instructor perspective, he don’t really need to know about the type of vehicle.</p><p>So, based on type of “Vehicle” at the moment, the “Start()” operation should behave. The Vehicle object need to exhibit polymorphism based on what object it represents dynamically during the run-time. This is called “Dynamic Polymorphism”.</p><p>As we all know, this is achieved by the keyword “<strong><em>virtual</em></strong>”. It internally instructs the compiler to expect a surprise when this particular function is called. Ok, Enough! I think, that would have given a fair level of understanding on “<strong><em>Dynamic Polymorphism</em></strong>”.</p><blockquote><strong>What is “Static Polymorphism”?</strong></blockquote><p>There is “<strong><em>Compile time polymorphism</em></strong>” and “<strong><em>Run Time polymorphism</em></strong>”. Everything goes good, correct? Then what is this “<strong><em>Static Polymorphism</em></strong>”?</p><p>When Mr.Real Poly (run time polymorphism) is proud about his camouflage behavior, he comes with a price. You guys must have heard about <strong><em>Virtual table and Virtual pointers</em></strong>. I don’t want to get into the details but just think that it is some <strong><em>dictionary </em></strong><em>data structure</em> maintained by your compiler. It is referred in run-time. If the list is big and complex, we definitely lose sometime in achieving the run time polymorphism beneath.</p><p>Practically, the time we lose is negligible if your develop a normal application program. However, there are some memory intrusive development where every CPU cycle is important. In such development environment, they consider “Virtual Tables” as costly affair, but still want to achieve “Runtime polymorphism”.</p><blockquote><strong>Example Code</strong></blockquote><p>Let’s quickly start with a “<strong><em>Run time polymorphism</em></strong>” example and see how we can convert it to “<strong><em>Static polymorphism</em></strong>”</p><pre>using namespace std;<br>class ETL<br>{<br>   public:<br>     void doAction()<br>     {<br>       Extract();<br>       Transform();<br>       Load();<br>     }<br>   private:<br>     void Extract() { cout &lt;&lt; &quot;Extract data&quot; &lt;&lt; endl; }<br>     virtual void Transform() = 0;<br>     void Load() { cout &lt;&lt; &quot;Load to DB&quot; &lt;&lt; endl; }<br>};</pre><pre>class CSV_data : public ETL<br>{<br>   private:<br>     void Transform() { cout &lt;&lt; &quot;Transform as Comma separated files&quot; &lt;&lt; endl; }<br>};</pre><pre>int main()<br>{<br>   CSV_data cData;<br>   cData.doAction(); // calls virtual Transform() internally<br>   return 0;<br>}</pre><p>If you notice the above example, it is a simple ETL process which performs <em>doAction() </em>in base class. However, the <em>Transform()</em> algorithm varies depends on the derived class i.e., CSV_data. Assume, you have multiple derived classes based the data formats you support. It would lead to too many virtual tables.</p><p>Now, before converting to “Static Polymorphism”, let me quickly explain what we have achieved by this dynamic polymorphism and what we should not lose after conversion too.</p><ol><li>It got “Is-a” relationship between Base and Derived class.</li><li>Base class implements a holistic action on the object.</li><li>Derived class specializes a part of it as per it’s need.</li><li>Driver/Client code do not know anything about all the above.</li></ol><p>Let’s convert now:</p><pre><strong>template &lt;typename T&gt; class ETL</strong><br>{<br>   public:<br>      void doAction()<br>      {<br>        Extract();<br>        Transform();<br>        Load();<br>      }<br>   private:<br>      void Extract() { cout &lt;&lt; &quot;Extract data&quot; &lt;&lt; endl; }<br>      void Transform() { <strong>static_cast&lt;T*&gt;(this)-&gt;Transfer();</strong> }<br>      void Load() { cout &lt;&lt; &quot;Load to DB&quot; &lt;&lt; endl; }<br>};</pre><pre>class CSV_data : <strong>public ETL&lt;CSV_data&gt;</strong><br>{<br>    private:<br>      void Transform() { cout &lt;&lt; &quot;Transfer as Comma separated files&quot; &lt;&lt; endl; }<br>};</pre><pre>int main()<br>{<br>   CSV_data cData;<br>   cData.doAction(); // calls virtual Transform() internally<br>   return 0;<br>}</pre><p>We introduced 3 changes:</p><ol><li>We converted Base class ETL as Template class.</li><li>Transform() function is no more a virtual function in base class. We <em>static cast</em>-ed with template variable and it calls function based on it.</li><li>In derived class we inherited ETL template class with our own derived class passed in as parameter.</li></ol><p>After doing this, we have never lost any of those 4 points discussed. We achieved a perfect polymorphism during the “compile time” itself. This is called “<strong><em>Static Polymorphism</em></strong>” in real sense.</p><blockquote><strong>Bonus Points</strong></blockquote><ol><li>This way of template programming is called <strong>CRTP</strong> (<strong>Curiously Recurring Template Pattern</strong>). CRTP is not all about “Static Polymorphism”. It is one of the use case of CRTP. CRTP is a broader topic by itself.</li><li>Moving “Run time” complexities to “compile time” using template as a tool is also called <strong>Template Meta Programming</strong> (<strong>TMP</strong>). Again, TMP is a broader topic and this is just a tip of iceberg.</li></ol><p>The reason for mentioning CRTP and TMP is to create interest and I except you to go and google about it. This article and discussion is very minimal and it is not talking fully about it in any sense.</p><p>Thanks for reading this article. Enjoy the day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45edb800e338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Injection” lost the number 1 spot!]]></title>
            <link>https://medium.com/@daloukalai/injection-lost-the-number-1-spot-7667c1e32c02?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/7667c1e32c02</guid>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[security-vulnerabilities]]></category>
            <category><![CDATA[top-10-2021]]></category>
            <category><![CDATA[sast]]></category>
            <category><![CDATA[appsec]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 06:48:01 GMT</pubDate>
            <atom:updated>2021-10-11T06:48:01.675Z</atom:updated>
            <content:encoded><![CDATA[<p>For the people who are thinking “Injection” as some COVID drug administered into person’s body, please ignore the discussion and move on. :) You have been traced to the wrong link. “Injection” got a different meaning in Application Security world.</p><p>Yes, Injection moved to Number 3 position in OWASP Top 10 for 2021. It was ruling the Number 1 position for <strong>more than decades</strong> and it was rightly so. It was the most dangerous Security threat which ruled the roost. Readers who have the interest to get to know about OWASP, Application Security, Security vulnerabilities, SQL Injection etc., please read it further, I will take you through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*kV-bKZS4Y8MKGWVatWzdIA.jpeg" /></figure><blockquote><strong>Application Security and Vulnerabilities.</strong></blockquote><p>Let me explain in simple terms. Any software product, irrespective of the programming languages we use for development, is prone to errors in the code. I am not talking about logical or compilation errors which would get caught during the build. But some “<em>problems</em>” would lead to big security loophole through external means. This cannot be caught through code review or build failure. They can be caught only by running a <em>SAST/DAST*</em> tool. Those are called “<strong><em>Vulnerability</em></strong>”. The field or area dealing these “<em>Vulnerabilities</em>” and “<em>Security Hotspot</em>” is called <strong><em>Application Security</em></strong>.</p><blockquote><strong>What is OWASP?</strong></blockquote><p>There are many consortium and open source communities doing research on this Application Security area and creates the list of most dangerous vulnerabilities existing in this world. One such non-profit foundation is OWASP (<em>The Open Web Application Security Project</em>), which is the <em>de facto</em> standard followed in many companies. What I mean is - In the real world scenario, products would run a SAST/DAST tool to identify the vulnerabilities present in their product. If the vulnerabilities identified are part of OWASP top 10, they would try to clear it off on top priority before making the release. Well, if it is <em>Numero Uno</em> vulnerability , I don’t need to say. That’s why SQL/Command Injections had the traction of people till date.</p><blockquote><strong>SQL Injection</strong></blockquote><p>Though there are many types of “<strong><em>Injection</em></strong>”, the most important and the common one is <strong><em>SQL injection</em></strong>. Indeed, when OWASP’s top 10 talk about Injection category, it majorly concerns on SQL and <em>Command Injection**</em>. Other injections also important but they are little uncommon. Some people categorize <strong><em>XSS</em></strong> under injection, but XSS is a topic and a category (Currently it takes Number 7 spot in OWASP) by itself. It will not come under “<em>Injection</em>” category of this list at least.</p><blockquote><strong>SQL Injection Examples</strong></blockquote><p>First of all, irrespective of the Relational DB you design for your DB layer ( <em>DB2/SQL server/ Oracle etc.</em>), the SQL syntax for CRUD operations are same. Again, irrespective of the programming language you choose for Front-end/Middle-tier, you need to interact with DB Layer (if it is RDBMS) through SQL query only. This would gives me a freedom to make a statement “<strong><em>If you choose to use tables in your application, the SQL query is the only way to interact to your DB irrespective of the programming language you choose to interact with</em></strong>”.</p><p>Let me tell you how the CRUD operations are exploited by “SQL Injection” with an example. Consider a SELECT query in “<em>TypeScript</em>”. It will look harmless as below:</p><pre>mycon.connect(function (err) {</pre><pre>mycon.query(&#39;SELECT * FROM users WHERE id = &#39; + <strong>userinput</strong>, (err, res) =&gt; { }); </pre><pre>});</pre><p>Now, let us assume your ‘<em>userinput</em>’ variable is passed by customer through GET/POST API without much validation. Any cheeky customer can give the input as “123 OR 1=1”. This will make the SQL query to look as below:</p><pre>SELECT * FROM users WHERE id = 123 OR 1=1;</pre><p>Can you see the WHERE condition is compromised introducing an “OR”? And the condition “1=1” is universally true always. Thus the query always satisfies the condition irrespective of user ID. He can easily get the details of full table without even knowing an user ID.</p><blockquote><strong>Remediation</strong></blockquote><p>Though SQL injection is very dangerous, it is very easy to remediate. Firstly, never use formatting strings to add parameters to SQL Query. Always add parameters to SQL queries using <strong>SQL binding mechanisms</strong> provided with language syntax as given below. If not available in your language, try to hard code the conditions and do not use it dynamically. This will save you life! :)</p><pre>mycon.connect(function (err) {</pre><pre>mycon.query(&#39;SELECT * FROM users WHERE id = <strong><em>?</em></strong>&#39; + <strong><em>[userinput]</em></strong>, (err, res) =&gt; { });</pre><blockquote><strong>What it means by losing the top spot?</strong></blockquote><p>So, SQL Injection lost top spot and do we need to take it lightly now? <strong>Never</strong>. Anything which is in OWASP Top 10 need to be taken seriously. The reason why it lost the number one position is may be because:</p><ol><li>Advent use of NOSQL DBs and a different format of query structuring other than SQL.</li><li>Architect’s reduced design thought of using RDBMS in modern products.</li><li>Existing products with RDBMS design are already vigilant to take care of SQL Injection.</li></ol><p>That’s all for now folks! Hope you got the concepts in a simple and easy language. Shout it out if you need more details.</p><p><em>*SAST/DAST — Static Application Security Testing/ Dynamic Application Security testing are broad category of techniques used to capture vulnerabilities.</em></p><p><em>**Command Injection — I am ignoring it in this discussion because they are start forward and the APIs/Commands will differ with programming languages. I don’t want to choose a language or OS CLI commands and discuss about it. May be we can have it in future article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7667c1e32c02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Double Dispatching in C++]]></title>
            <link>https://medium.com/@daloukalai/double-dispatching-in-c-df76724cf321?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/df76724cf321</guid>
            <category><![CDATA[visitor-pattern]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[double-dispatch]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 17:32:49 GMT</pubDate>
            <atom:updated>2021-10-08T17:53:49.719Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I came across a very interesting discussion that someone asking me if C++ supports “<em>Double Dispatching</em>”. I was like, <em>Wait! What you mean by that?</em> Because, I know “<em>dispatching</em>” is nothing but calling some method “<em>virtually</em>” in runtime and that’s about it. Luckily, I was indeed correct and got to know that it is called “<em>Single Dispatching</em>”, technically. Then I was curious to know about “<em>Double dispatching</em>”. Eventually, I got to know that <strong>C++ does not support</strong> “<em>Double Dispatching</em>” inherently in its language syntax. However, we can do it with a help of a pattern.</p><p>Come, let’s delve into details!</p><blockquote><strong>What is Dispatching?</strong></blockquote><p>Dispatching literally means, sending something to a destination. In C++ also it carries the same meaning. When you call a function/method from your main method, you would reach a different address space and start executing the method. This is called “<em>dispatching</em>”.</p><p>If the designated method you call is not a virtual function, then it will be chosen at the compile time. This is called “<em>Static Dispatch</em>”.</p><p>If the designation method you call is a virtual function, you never know which method you are calling until the runtime. This is called “<em>Dynamic Dispatch</em>”.</p><p>Both Static and Dynamic dispatches are “<em>Single Dispatch</em>” in literal sense. However, it is prevalent and common to call “<em>Dynamic dispatch</em>” as “<em>Single Dispatch</em>” in many contexts.</p><blockquote><strong>Double Dispatch</strong></blockquote><p>When one more virtual method doing an additional indirection in the above scenario, then a double dispatch scenario would occur. If you are confused, have a look at the example below. It is simple and straight forward. I don’t think I need to explain the below code:</p><pre>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>class Bird<br>{};<br>class Chicken : public Bird<br>{};</pre><pre>class Animal<br>{<br> public: <br>   virtual void eats(Bird *b)<br>   {<br>      cout &lt;&lt; &quot;Animal Eats Bird&quot; &lt;&lt; endl;<br>   }<br>   virtual void eats(Chicken *b)<br>   {<br>      cout &lt;&lt; &quot;Animal Eats Chicken&quot; &lt;&lt; endl;<br>   }<br>};</pre><pre>class Tiger : public Animal<br>{<br>  public:<br>    void eats(Bird *b)<br>    {<br>        cout &lt;&lt; &quot;Tiger Eats Bird&quot; &lt;&lt; endl;<br>    }<br>    void eats(Chicken *b)<br>    {<br>       cout &lt;&lt; &quot;Tiger Eats Chicken&quot; &lt;&lt; endl;<br>    }<br>};</pre><pre>int main()<br>{<br>  Animal *tiger = new Tiger();<br>  Bird *chicken = new Chicken();<br>  // Double-dispatch<br>  // 1. Animal is virtually calling tiger<br>  // 2. Bird is virtually calling Chicken<br>  // Thus double dispatch, which is not possible in C++<br>  tiger-&gt;eats(chicken);<br>  return 0;<br>}</pre><p>Guess the output. So, you are expecting “Tiger Eats Chicken”, am I right?</p><p>No, you will get “Tiger Eats Bird”. I will explain why.</p><p>In the code above, you have a virtual method in <strong>Animal</strong> class (pointing to derived class object <strong>Tiger</strong> )is calling a Virtual object of <strong>Bird</strong> class (pointing to derived class object <strong>Chicken</strong>). Here 2 Virtual Tables are involved. This is not possible in C++. The method is called based on the first indirection only (Animal-&gt;Tiger) and not based on both in-directions (Animal-&gt;Tiger &amp; Bird-&gt;Chicken). This is otherwise called “Double dispatching”.</p><p>But it is possible in C++ indirectly by many ways. The best way to achieve it is through “<strong>Visitor Pattern</strong>”. Visitor is by the far the complex pattern and most misunderstood pattern in the real-world scenario. One of the main goal of visitor is to achieve double-dispatching. I would leave it at here and want you to explore the beautiful visitor pattern by yourself. Possibly, I will try to continue about it in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df76724cf321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introductory Note!]]></title>
            <link>https://medium.com/@daloukalai/introductory-note-2c09475073b4?source=rss-86132a4da462------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c09475073b4</guid>
            <category><![CDATA[this-is-me]]></category>
            <dc:creator><![CDATA[Dalou Kalaivendhan]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 10:19:03 GMT</pubDate>
            <atom:updated>2021-10-08T10:19:03.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone!</p><p>This is Dalou Kalaivendhan, a Software Developer and a Programming Enthusiast from India. I would love to explore MEDIUM as a blogging site and keep adding my daily learning here. I would like to keep adding my stories, quick learning, fun stuffs, anecdotes without much type checking, a raw note — more like a personal diary. But definitely a diary which can be read by anyone. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*TOoVm6N_X2BJh472wFjz6w.jpeg" /></figure><p>And the funny guy above is me! :)</p><p>Cheers…. and more to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c09475073b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>