<?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 S D on Medium]]></title>
        <description><![CDATA[Stories by S D on Medium]]></description>
        <link>https://medium.com/@satyadirisala?source=rss-243acfa1073d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by S D on Medium</title>
            <link>https://medium.com/@satyadirisala?source=rss-243acfa1073d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:24:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyadirisala/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[Tricky C++ code Snippets (Types)]]></title>
            <link>https://medium.com/@satyadirisala/tricky-c-code-snippets-types-454159749871?source=rss-243acfa1073d------2</link>
            <guid isPermaLink="false">https://medium.com/p/454159749871</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[type-safe]]></category>
            <dc:creator><![CDATA[S D]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 06:33:59 GMT</pubDate>
            <atom:updated>2025-03-10T06:33:59.334Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. What does this code output, and why?</strong></p><pre>int main() {<br>    unsigned short x = 65535; // Max value for 16-bit unsigned short<br>    x = x + 1;<br>    std::cout &lt;&lt; x;<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: <em>This tests understanding of unsigned integer overflow. When x (max value 65535) is incremented, it wraps around to 0 due to modular arithmetic in unsigned types. The output is 0, and candidates might miss this if they confuse signed and unsigned behavior.</em></blockquote><p><strong>2. Why does this comparison fail unexpectedly?</strong></p><pre>int main() {<br>    double a = 0.1;<br>    double sum = 0.0;<br>    for (int i = 0; i &lt; 10; i++) {<br>        sum += a;<br>    }<br>    if (sum == 1.0) {<br>        std::cout &lt;&lt; &quot;Sum is 1.0&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;Sum is not 1.0&quot;;<br>    }<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: Floating-point arithmetic is imprecise due to binary representation. Adding 0.1 ten times doesn’t exactly equal 1.0 (it might be something like 0.9999999999999999), so the output is “Sum is not 1.0”. This tests awareness of floating-point pitfalls and the need for epsilon comparisons.</blockquote><p><strong>3. What is the output of this code, and why?</strong></p><pre><br>int main() {<br>    int a = -5;<br>    unsigned int b = 10;<br>    std::cout &lt;&lt; (a + b);<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: This involves signed-to-unsigned conversion. When a (-5) is added to b (10), a is converted to an unsigned int, becoming a large positive number (e.g., 4294967291 on a 32-bit system). The result is 4294967291 + 10 = 4294967301, but since it exceeds the max unsigned int, it wraps to 5. The output is 5, testing knowledge of type promotion and overflow.</blockquote><p><strong>4. What’s wrong with this loop, and how does it behave?</strong></p><pre><br>int main() {<br>    unsigned int i = 5;<br>    while (i &gt;= 0) {<br>        std::cout &lt;&lt; i &lt;&lt; &quot; &quot;;<br>        i--;<br>    }<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: Using unsigned int in a countdown loop is dangerous. When i reaches 0 and decrements, it wraps to the maximum unsigned int value (e.g., 4294967295). This creates an infinite loop (or nearly infinite), printing 5 4 3 2 1 0 4294967295 …. It tests understanding of unsigned underflow.</blockquote><p><strong>5. What does this code print, and why?</strong></p><pre>int main() {<br>    char c = 127;<br>    c++;<br>    std::cout &lt;&lt; static_cast&lt;int&gt;(c);<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: This depends on whether char is signed or unsigned by default (implementation-defined). If char is signed, 127 is the max value, and c++ overflows to -128 due to signed overflow (undefined behavior, but typically wraps). If unsigned, it becomes 128. The output is likely -128 on most systems, testing knowledge of char behavior and overflow.</blockquote><p><strong>6. Why might this code produce unexpected results?</strong></p><pre>int main() {<br>    short a = 32767; // Max value for 16-bit signed short<br>    int b = a + 1;<br>    std::cout &lt;&lt; b;<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: Adding 1 to the max short (32767) promotes a to int before the addition, so b becomes 32768 without overflow. However, if the candidate assumes short overflow occurs first, they might expect undefined behavior or wrapping to -32768. This tests type promotion rules.</blockquote><p><strong>7. What does this code output, and why?</strong></p><pre>int main() {<br>    bool b = -1;<br>    if(b){ std::cout &lt;&lt; &quot;true\n&quot; ;} else {std::cout &lt;&lt; &quot;false\n&quot;;}<br>    std::cout &lt;&lt; b;<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: Assigning -1 to a bool converts it to true, since any non-zero value becomes true. The output is true/1 (the integer representation of true). This tests understanding of bool conversion rules</blockquote><p><strong>8. What’s the issue with this type conversion?</strong></p><pre>int main() {<br>    unsigned int u = 4294967295; // Max 32-bit unsigned int<br>    int i = u;<br>    std::cout &lt;&lt; i;<br>    return 0;<br>}</pre><blockquote><strong>Why it’s tricky</strong>: Converting a large unsigned int to a signed int causes overflow if it exceeds int’s max (2147483647). On a 32-bit system, 4294967295 becomes -1 due to two’s complement wrapping. The output is -1, testing knowledge of signed/unsigned conversion pitfalls.</blockquote><p>These questions challenge candidates on subtle C++ behaviors like type promotion, overflow, and precision issues.</p><h3>C++ concepts Discussed:</h3><ul><li><strong>Unsigned Overflow</strong>: Unsigned integers wrap around (e.g., max value + 1 becomes 0, 0–1 becomes max).</li><li><strong>Floating-Point Precision</strong>: Binary representation causes small errors, so equality checks like sum == 1.0 may fail.</li><li><strong>Type Promotion</strong>: Mixed-type expressions promote smaller types to larger ones, potentially altering results.</li><li><strong>Signed vs. Unsigned Comparison</strong>: Signed negatives become large unsigned values, breaking comparisons (e.g., -1 &lt; 1u is false).</li><li><strong>Loop Conditions</strong>: Unsigned types in loops (e.g., i &gt;= 0) can cause infinite loops due to wrapping.</li><li><strong>Char Behavior</strong>: char may be signed or unsigned; signed overflow is undefined, unsigned wraps.</li><li><strong>Bool Conversion</strong>: Non-zero values become true, zero becomes false.</li><li><strong>Type Conversion</strong>: Large unsigned-to-signed conversions can overflow, yielding negatives (e.g., 4294967295 to int is -1).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454159749871" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Dynamic Dispatch: A Deep Dive into Virtual Functions, vptr, and vtable]]></title>
            <link>https://medium.com/@satyadirisala/demystifying-dynamic-dispatch-a-deep-dive-into-virtual-functions-vptr-and-vtable-9574c1ad9bed?source=rss-243acfa1073d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9574c1ad9bed</guid>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[oops-interview-questions]]></category>
            <category><![CDATA[virtual]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[S D]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 21:30:39 GMT</pubDate>
            <atom:updated>2023-10-14T21:30:39.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic dispatch (or late binding) is a core concept in object-oriented programming, especially when dealing with virtual functions. Let’s break it down step by step:</h3><p><strong>What is Dynamic Dispatch?</strong></p><p>Dynamic dispatch is a mechanism by which a call to an overridden function (or method) is resolved dynamically at runtime, rather than at compile-time. This means that the actual function that gets executed is determined based on the object’s actual type, rather than its static type.</p><p><strong>The Role of Virtual Functions:</strong></p><p>In languages like C++, a function is made “virtual” to indicate that it can be overridden by derived classes and that dynamic dispatch should be used when invoking this function on a pointer or reference to the base type.</p><p><strong>How Does It Work?</strong></p><p><strong><em>When a function is declared as virtual in a base class:</em></strong></p><ol><li>A table called the **vtable** (virtual table) is created for that class</li><li>Every class that inherits from this base class and overrides this virtual function gets its own vtable</li><li>The vtable contains addresses of the actual functions that should be called for objects of a particular type</li></ol><p><strong><em>When a virtual function is called on an object:</em></strong></p><ol><li>The system looks up the object’s vtable based on its actual type</li><li>It finds the address of the function to execute</li><li>It calls the function at that address</li></ol><p><strong>Example</strong>:</p><p>Consider the classic example of shapes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*5mrq6v3M5BW1amuAq2M0bQ.png" /></figure><p>In this example, even though the `render` function takes a reference to a `Shape`, the actual function called (i.e., the `draw` method) is determined dynamically at runtime based on the actual type of the object passed in (`Circle` or `Square`). This is possible because of dynamic dispatch and the use of virtual functions.</p><p><strong>Key Takeaways</strong>:</p><blockquote>Dynamic dispatch enables polymorphism, allowing objects of different types to be treated as if they are objects of the same type</blockquote><blockquote>Virtual functions are the foundation for enabling dynamic dispatch in languages like C++</blockquote><blockquote>Overhead: Dynamic dispatch introduces a slight overhead due to the vtable lookup, but this is generally negligible in practice</blockquote><p>Let’s visualize the vtable setup for our classes</p><h3>vtable:</h3><p>Every class with a virtual function will have its own vtable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvFOdE2l0mfLA9XjxuQofQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU4Pb3q2-m2vpQzYlKoREA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT27rShr9UCFszGMAOcwrw.png" /></figure><h3>vptr (Virtual Pointer):</h3><p>Each object of a class will have its own vptr pointing to its class&#39;s vtable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7GY2y26LKTgnFptJesdiA.png" /></figure><h3>How the Call Happens:</h3><p>For the above example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LM4f445Ts37lIR1tvbpaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xcmpn1ivM09y1SGXs8GewQ.png" /></figure><blockquote>The compiler sees shapePtr-&gt;draw().</blockquote><blockquote>It fetches the vptr from the shapePtr.</blockquote><blockquote>Using this vptr, it accesses the Circle&#39;s vtable and fetches the function pointer for draw, which points to Circle::draw().</blockquote><blockquote>Circle::draw() is then called</blockquote><p>Let’s distinguish between compile-time and runtime activities for the concepts of vptr and vtable in the context of the example:</p><h3>Compile-time:</h3><ol><li>Creation of vtables:</li></ol><ul><li>The compiler constructs vtables for each class that has or inherits a virtual function</li><li>For our example:</li><li>A vtable for Shape is created with a pointer to Shape::draw()</li><li>A vtable for Circle is created with a pointer to Circle::draw()</li><li>A vtable for Square is created with a pointer to Square::draw()</li></ul><p>2. Generation of vptr in the object layout:</p><ul><li>The compiler inserts the vptr into the memory layout of each object that belongs to a class with a virtual function.</li></ul><p>3. Binding of virtual function calls:</p><ul><li>When the compiler encounters a virtual function call, it generates code to fetch the correct function pointer from the vtable using the vptr. The actual lookup, though, will be deferred until runtime</li></ul><h3>Runtime:</h3><ol><li>Initialization of vptr:</li></ol><ul><li>When an object is created (either on the stack or heap), its constructor initializes the vptr to point to its class&#39;s vtable.</li><li>For instance, when a Circle object is created, its vptr is set to point to the Circle class&#39;s vtable.</li></ul><p>2. Dynamic dispatch of virtual functions:</p><ul><li>When a virtual function is called through a pointer or reference, the following happens:</li><li>The vptr of the object is accessed to find the address of the vtable.</li><li>The correct function pointer is fetched from the vtable.</li><li>The function is then invoked using that function pointer.</li><li>For our example, if shapePtr-&gt;draw(); is executed and shapePtr points to a Circle object, then Circle::draw() is dynamically dispatched and executed.</li></ul><blockquote>In summary, the <em>setup for dynamic dispatch</em> (like creating vtables and inserting vptr into object layouts) is done during <em>compile-time</em>. The actual <em>dispatch</em> (determining which function to call) is done at <em>runtime</em>.</blockquote><h3><strong>Reflective Queries for Mastery of the Topic:</strong></h3><p>As we conclude our exploration, here are some questions to ponder</p><ol><li>What prompts the compiler to generate a vtable for a class?</li><li>How do virtual destructors affect the vtable?</li><li>Can a class have multiple vtables?</li><li>Why is it dangerous to call a virtual function from a constructor or destructor?</li><li>How does dynamic dispatch affect inline optimizations?</li><li>What happens if a derived class doesn’t override a virtual function?</li><li>How does adding or removing a virtual function affect binary compatibility in a library?</li><li>Is the layout and mechanism of vptr and vtable consistent across different compilers or platforms?</li><li>Why might you mark a function as virtual even if you don’t intend for it to be overridden?</li><li>How does the final keyword (in languages that support it) affect virtual functions and dynamic dispatch?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9574c1ad9bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>