<?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 Pratik Bhaskar Katkar on Medium]]></title>
        <description><![CDATA[Stories by Pratik Bhaskar Katkar on Medium]]></description>
        <link>https://medium.com/@pratikkatkar13?source=rss-12008e6cb832------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yX5azQAGShiTt9j-xuE4yQ.jpeg</url>
            <title>Stories by Pratik Bhaskar Katkar on Medium</title>
            <link>https://medium.com/@pratikkatkar13?source=rss-12008e6cb832------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:43:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pratikkatkar13/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[Advanced C++ (Part 2) — Demystifying Lambda Expressions in Modern C++]]></title>
            <link>https://medium.com/@pratikkatkar13/advanced-c-part-2-demystifying-lambda-expressions-in-modern-c-8a9c821ab0f0?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9c821ab0f0</guid>
            <category><![CDATA[captures-in-lambda]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[applications-of-lambda]]></category>
            <category><![CDATA[modern-cpp]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 11:24:42 GMT</pubDate>
            <atom:updated>2025-06-23T11:24:42.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced C++ (Part 2) — Demystifying Lambda Expressions in Modern C++</h3><h4><strong>Modern C++ (from C++11 onwards) introduced lambda expressions , a powerful feature that allows you to define anonymous functions directly in your code. Lambdas are concise, expressive, and perfect for cases where you’d otherwise define a small function or use a function pointer.</strong></h4><h4>What is a Lambda Expression?</h4><p>A lambda expression is an <strong>unnamed function object</strong> that can capture variables from its surrounding scope also we can add parameters like in function and return type too. Here’s the basic syntax:</p><pre>[capture](parameters) -&gt; return_type {<br>    // function body<br>};<br><br>// in many cases, C++ can deduce the return type.<br>[capture](parameters) {<br>    // function body<br>};<br></pre><h4>Basic Lambda —</h4><p>No return type, No parameters and no captures.<br>Here we are not naming the lambda but just to make easy we are storing the lambda function in some variable so we can call it whenever being needed that doesn&#39;t mean we named lambda <strong>or else you will say that if lambda is unnamed function object how come we named it ??</strong>. Also remember lambda is function object so we are using ‘auto’ to give the compiler the right to deduce its type.</p><pre>auto greet = []() {<br>    std::cout &lt;&lt; &quot;Hello from Lambda!&quot; &lt;&lt; std::endl;<br>};<br>greet(); <br>// Output: Hello from Lambda!</pre><h4>Lambdas with Parameters —</h4><p>Having parameters but no return type and no captures.</p><pre>auto show = [](int a, int b) {<br>    std::cout &lt;&lt; &quot;a = &quot; &lt;&lt; a &lt;&lt; &quot; b = &quot; &lt;&lt; b &lt;&lt; std::endl;<br>};<br><br>show(3, 4); <br>// Output: a = 3 b = 4</pre><h4>Lambdas return type —</h4><p>Having parameters and return type but no captures.</p><pre>auto add = [](int a, int b) -&gt; int {<br>    return a + b ;<br>};<br><br>std::cout&lt;&lt;add(3,4); <br>// Output: 7</pre><h4>What is Capture in Lambdas?</h4><p>A <strong>capture</strong> allows a lambda to access variables that are defined outside its body — i.e., variables in the scope where the lambda is created. These can be captured in <strong>two main ways</strong>:</p><ul><li><strong>By value</strong>: Copy the variable into the lambda.</li><li><strong>By reference</strong>: The lambda refers to the original variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*0MEa2ANy1pqhqHoFJ64ARQ.png" /></figure><h3>Types of Captures in C++</h3><h4><strong>1. Capture by Value </strong><strong>[=]</strong></h4><p>Captures <strong>all local variables</strong> used inside the lambda by <strong>value (copy)</strong>.<br>-&gt; Safe for read-only use.<br> -&gt; Cannot modify captured variables unless mutable is used.</p><pre>int a = 10;<br>auto lambda = [=]() {<br>    std::cout &lt;&lt; &quot;a = &quot; &lt;&lt; a &lt;&lt; std::endl; // Uses a copy of `a`<br>};<br>lambda();<br>// Output - 10;</pre><p>By default, variables captured by value are read-only. To modify them, use the mutable keyword:</p><pre>int x = 10;<br>auto change = [=]() mutable {<br>    x = 20; // allowed due to mutable<br>    std::cout &lt;&lt; x &lt;&lt; std::endl;<br>};<br>change(); // Output: 20<br>std::cout &lt;&lt; x &lt;&lt; std::endl; // Output 10 (original remains unchanged) as copy is created</pre><h4>2. Capture by Reference [&amp;]</h4><p>Captures <strong>all local variables</strong> used inside the lambda by <strong>reference</strong>.<br>-&gt; Use this when you want the lambda to <strong>modify external variables</strong>.<br> -&gt; Be careful with lifetime issues, especially in asynchronous or delayed execution.</p><pre>int a = 10;<br>auto lambda = [&amp;]() {<br>    a += 5; // Modifies original `a`<br>    std::cout &lt;&lt; a&lt;&lt; std::endl; <br>};<br>lambda(); // Output: 15<br>std::cout &lt;&lt; a; // Output: 15</pre><h4>3. Capture Specific Variables by Value [x, y]</h4><p>Capture only selected variables by value.<br>-&gt; Safer and more explicit than [=].</p><pre>int x = 5, y = 10;<br>auto lambda = [x, y]() {<br>  // if we want to modify use a mutable keyword and modification takes placed with lambda scope only does not affect original values.<br>    std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y;<br>};<br>lambda(); // Output: 5, 10<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y; // Output: 5, 10</pre><h4>4. Capture Specific Variables by Reference [&amp;x, &amp;y]</h4><p>Capture only selected variables by reference.<br>-&gt; Safer and more explicit than [&amp;].</p><pre>int x = 5, y = 10;<br>auto lambda = [&amp;x, &amp;y]() {<br>    x += 5;<br>    y += 10;<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y;<br>};<br>lambda(); //Output: 10,20<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y; // Output: 10, 20</pre><h4>5. Mixed Capture [x, &amp;y]</h4><p>You can mix value and reference captures.<br>-&gt; Great for fine-grained control over what can be modified.</p><pre>int x = 3, y = 4;<br>auto lambda = [x, &amp;y]() {<br>    // x is captured by value (copy) – changes inside won&#39;t affect outer x<br>    // y is captured by reference – changes affect outer y<br>    // x += 10; // won&#39;t compile unless &#39;mutable&#39; is added<br>    std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; (y+= 4) &lt;&lt; std::endl;<br>};<br>lambda(); // Output: 3, 8<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y; // Output: 3, 8</pre><h4><strong>6. Default + Exceptions </strong><strong>[=, &amp;y] or </strong><strong>[&amp;, x]</strong></h4><p>Specify a default capture, then override for individual variables.<br>-&gt; Useful in larger lambdas where most variables follow one style, and only a few are different.<br> → <strong>[=, &amp;y]</strong><br>Default: Capture all used variables by value.<br>Exception: Capture ‘y’ by reference.<br> → <strong>[&amp;, x]</strong><br>Default: Capture all used variables by reference.<br>Exception: Capture ‘x’ by value.</p><pre>// Example 1- [=, &amp;y]<br><br>int x = 10, y = 20;<br>auto lambda = [=, &amp;y]() {<br>    // x is by value, y by reference<br>    // x is captured by value (copy) – changes inside won&#39;t affect outer x<br>    // y is captured by reference – changes affect outer y<br>    // x += 10; // won&#39;t compile unless &#39;mutable&#39; is added<br>    y += x;<br>    std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y;<br>};<br>lambda(); // Output - 10, 30<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y; // Output - 10, 30</pre><pre>//Example 2 - [&amp;, x]<br><br>int x = 10, int y = 5;<br>auto lambda = [&amp;, x]() {<br>    // y is by reference → can be modified<br>    // x is by value → cannot be modified unless mutable<br>    y += 5;   <br>    // x++;   Error<br>    std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y &lt;&lt; std::endl;<br>};<br><br>lambda();  // Output: 10, 10<br>std::cout &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y &lt;&lt; std::endl;  // Output: 10, 10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*98C8i1zbZuUzDDLi5PwzSQ.png" /></figure><h4><strong>7. Initialization Capture (</strong><strong>[x = expr])</strong> – Available since C++14</h4><p>This capture form allows you to:<br> → Assign expressions or computed values directly to the captured variable.<br> → Capture <strong>move-only types</strong> like unique pointer .<br>[x = expr] means `x` is a new variable inside the lambda, initialized with `expr.</p><pre>// Example 1 - You can’t capture unique_ptr by copy ([=]) <br>// since it’s non-copyable. But [p = std::move(ptr)] works, <br>// because it uses move semantics.<br><br>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>int main() {<br>    auto ptr = std::make_unique&lt;int&gt;(42);<br><br>    auto lambda = [p = std::move(ptr)]() {<br>        std::cout &lt;&lt; *p &lt;&lt; std::endl;<br>    };<br><br>    lambda();               // Output: 42<br>    // ptr is now nullptr (ownership moved into the lambda)<br>}</pre><pre> // Example 2 - lets you preprocess data or logic outside the lambda but still use the result inside.<br><br>int base = 10;<br>auto lambda = [square = base * base]() {<br>    std::cout &lt;&lt; &quot;Square is: &quot; &lt;&lt; square &lt;&lt; std::endl;<br>};<br><br>lambda(); // Output: Square is: 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*TKvGeV1RTtIhsI9k5DaMKw.png" /></figure><h4>8. Capture by this – Available since C++11</h4><p>Captures the current object pointer (this) so you can access <strong>members of a class</strong> inside the lambda. But if you <strong>store the lambda and run it later</strong>, and the object is <strong>already destroyed</strong>, using (this) becomes <strong>undefined behavior</strong>.</p><pre>#include&lt;iostream&gt;<br>class MyClass {<br>public:<br>    int value = 100;<br><br>    void run() {<br>        auto lambda = [this]() {  <br>            value += value; // modifies this-&gt;value (100 + 100 = 200)<br>            std::cout &lt;&lt; &quot;Inside lambda: &quot; &lt;&lt; value &lt;&lt; std::endl; //here value is equivalent to this-&gt;value<br>        };<br>        lambda(); // will print 200<br>    }<br><br>    void print() {<br>        std::cout &lt;&lt; &quot;In print(): &quot; &lt;&lt; value &lt;&lt; std::endl; // will print 200<br>    }<br>};<br>int main() {<br>    MyClass obj;<br>    obj.run();    // Modifies value: 100 → 200<br>    obj.print();  // Will show 200<br>    return 0;<br>}</pre><h4><strong>9. Capture by </strong><strong>*this</strong> – Available since C++17</h4><p>Captures <strong>a copy of the object</strong> (not a pointer). All member accesses happen on the <strong>copied object</strong>, not the original. This helps prevent issues if the original object is destroyed before the lambda runs.<br><strong>Always remember , [*this] captures a copy of the object by value, but every copy is made constant inside lambda (read only) in order to modify we use mutable but makes original object unmodified only.</strong></p><pre>#include&lt;iostream&gt;<br>class MyClass {<br>public:<br>    int value = 100;<br><br>    void run() {<br>        auto lambda = [*this]() mutable {  <br>            value += value; // modifies this-&gt;value (100 + 100 = 200)<br>            std::cout &lt;&lt; &quot;Inside lambda: &quot; &lt;&lt; value &lt;&lt; std::endl; //here value is equivalent to this-&gt;value<br>        };<br>        lambda(); // will print 200<br>    }<br><br>    void print() {<br>        std::cout &lt;&lt; &quot;In print(): &quot; &lt;&lt; value &lt;&lt; std::endl; // will print 100<br>    }<br>};<br>int main() {<br>    MyClass obj;<br>    obj.run();    // Modifies value: 100 → 200<br>    obj.print();  // Will show 100 <br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*GTdLVi9niXU5eAM8eIJcyA.png" /></figure><h4><strong>1. STL Algorithms (Sorting, Filtering, Transforming)</strong></h4><pre>// Example: Sorting with custom criteria<br><br>std::vector&lt;std::pair&lt;int, std::string&gt;&gt; data = {{2, &quot;two&quot;}, {1, &quot;one&quot;}, {3, &quot;three&quot;}};<br><br>std::sort(data.begin(), data.end(), [](const auto&amp; a, const auto&amp; b) {<br>    return a.first &lt; b.first;  // sort by first element in ascending <br>});</pre><h4>2. <strong>Asynchronous Execution (std::async, std::thread)</strong></h4><pre>std::future&lt;int&gt; future = std::async([]() {<br>    std::this_thread::sleep_for(std::chrono::seconds(1));<br>    return 42;<br>});<br><br>std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; future.get();  // Output: Result: 42</pre><h4>3. <strong>Callbacks and Event Handlers</strong></h4><pre>// Pseudo-GUI code<br>button.onClick([]() {<br>    std::cout &lt;&lt; &quot;Button clicked!&quot; &lt;&lt; std::endl;<br>});</pre><h4><strong>4. Custom Comparators in Data Structures</strong></h4><pre>std::priority_queue&lt;int, std::vector&lt;int&gt;, std::function&lt;bool(int, int)&gt;&gt; pq(<br>    [](int a, int b) { return a &gt; b; }  // min-heap comparator<br>);</pre><h4>5. Functional-style Pipelines with Ranges (C++20)</h4><pre>#include &lt;ranges&gt;<br><br>std::vector&lt;int&gt; nums = {1, 2, 3, 4, 5};<br><br>for (int x : nums | std::views::filter([](int n) { return n % 2 == 0; })) {<br>    std::cout &lt;&lt; x &lt;&lt; &quot; &quot;; // Output: 2 4<br>}</pre><h4><strong>6. Resource Cleanup (Custom Deleters)</strong></h4><p>Lambdas allow you to define a <strong>custom cleanup logic inline</strong> when the smart pointer is destroyed.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>int main() {<br>    auto fileDeleter = [](FILE* f) {<br>        if (f) {<br>            std::cout &lt;&lt; &quot;Closing file...&quot; &lt;&lt; std::endl;<br>            fclose(f);<br>        }<br>    };<br>    std::unique_ptr&lt;FILE, decltype(fileDeleter)&gt; file(fopen(&quot;data.txt&quot;, &quot;r&quot;), fileDeleter);<br>    // file will be closed automatically using the lambda when it goes out of scope<br>    return 0;<br>}</pre><h4>7. <strong>Test/Mock Functions (Unit Testing)</strong></h4><pre>auto isEven = [](int n) { return n % 2 == 0; };<br>assert(isEven(4));  </pre><h4>8. Stateful Closures (With Mutable or Captures)</h4><pre>int counter = 0;<br>auto countCalls = [&amp;counter]() mutable {<br>    return ++counter;<br>};<br><br>countCalls(); // 1<br>countCalls(); // 2</pre><h4>9. Visitor Pattern with std::variant and Lambdas</h4><p>std::variant&lt;T1, T2, ..., Tn&gt; is a type-safe alternative to unions, which means:<br><strong> → </strong>It can hold exactly one of the specified types at a time.<br><strong> →</strong> It’s part of the &lt;variant&gt; header.<br><strong> → </strong>Think of it like a container for one value, but that value can be of different possible types.<br><strong> →</strong> std::visit let you write different code paths for each type in a clean, safe way. To avoid unsafe typeid or dynamic_cast , Lambdas support generic code and make the visitor pattern much easier</p><pre>#include &lt;iostream&gt;<br>#include &lt;variant&gt;<br>#include &lt;string&gt;<br><br>int main() {<br>    std::variant&lt;int, float, std::string&gt; data;<br><br>    // data = 42;          // OK: holds int<br>    // data = 3.14f;       // OK: now holds float<br>    data = &quot;hello&quot;;     // OK: now holds string<br><br>    // Access using std::visit and lambda<br>    std::visit([](auto&amp;&amp; value) {<br>        std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>    }, data);<br>}</pre><h4><strong>10. Passing behavior</strong></h4><p>You want to <strong>restrict</strong> templates to only accept certain types — e.g., numbers only, not strings.</p><pre>#include &lt;concepts&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br><br>    // Lambda constrained to accept only integral (integer) types using C++20 concepts<br>    // Ensures &#39;add&#39; works only with types like int, char, long, etc. (not float, double or string)<br>    auto add = [](std::integral auto a, std::integral auto b) {<br>        return a + b;<br>    };<br><br>    std::cout &lt;&lt; add(5, 10) &lt;&lt; std::endl;  // OK<br>    // std::cout &lt;&lt; add(3.5, 2.2) &lt;&lt; std::endl;  // Compilation error<br>}</pre><p>Hence, Lambda expressions make C++ code cleaner, more concise, and closer to functional programming paradigms. From simple iteration to threading and sorting, lambdas are indispensable tools in a modern C++ developer’s toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9c821ab0f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Real-World Power of C++ in 2025: Still Relevant, Still Dominant]]></title>
            <link>https://medium.com/@pratikkatkar13/the-real-world-power-of-c-in-2025-still-relevant-still-dominant-4f894636baf3?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f894636baf3</guid>
            <category><![CDATA[cpp-usage]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[dominance-of-cpp]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 11:48:02 GMT</pubDate>
            <atom:updated>2025-06-15T11:55:32.334Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Many people today believe that C++ is outdated and replaced by Python, JavaScript, or Java. But that assumption is both oversimplified and misleading. While newer languages offer ease and speed of development, C++ continues to be the backbone of performance-critical, resource-constrained, and real-time systems.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*0wFZ9FGqi4S-mnHqldy9Rw.png" /></figure><h3>Where C++ Still Dominates ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*GrpN3FEDA_G62JKzZgysMA.png" /></figure><h3>1. Game Development —</h3><p>Game development requires <strong>real-time performance</strong>, precise memory management, and <strong>direct hardware access</strong> (like GPUs, controllers, etc.). C++ offers all of this with <strong>minimal runtime overhead</strong>.</p><p><em>— </em><strong><em>Real-World Examples:</em></strong><br>1. <strong>Unreal Engine</strong> (used in Fortnite, PUBG, Gears of War): Built in C++.<br>2. <strong>Unity</strong> (core parts): Though scripting is in C#, performance-critical internals are in C++.<br>3. <strong>EA, Rockstar, and Ubisoft</strong> use C++ for their AAA game engines.</p><p>— <strong>Technical Justification:<br></strong>1. <strong>Deterministic memory management</strong> via manual allocation.<strong><br>2. Object-oriented design</strong> fits well with entities like players, NPCs, weapons, etc.<br>3. <strong>Multithreading support</strong> for handling rendering, physics, input, and AI simultaneously.</p><h3>2. Operating Systems &amp; Browsers —</h3><p>Operating systems need <strong>low-level access to hardware</strong>, efficient use of memory, and extremely reliable performance. These systems can’t afford the overhead of garbage collection or interpreted runtimes.</p><p>— <strong>Real-World Examples:</strong><br>1. <strong>Windows</strong> (large parts written in C++).<br>2. <strong>macOS</strong> and <strong>Linux kernel modules</strong> rely on C and C++.<br>3. <strong>Web browsers</strong> like <strong>Google Chrome</strong>, <strong>Mozilla Firefox</strong>, <strong>Safari</strong> — their engines (V8, Gecko, WebKit) are in C++.</p><p>— <strong>Technical Justification:<br></strong>1. Pointer arithmetic, direct memory access, and custom memory allocators.<strong><br>2. </strong>Integration with hardware drivers, interrupt handling, and kernel modules.<br>3. <strong>Performance-critical rendering engines</strong> (e.g., for HTML, CSS, JS parsing) are optimized in C++.</p><h3>3. Embedded Systems &amp; IoT —</h3><p>These systems run on devices with limited CPU power, RAM, and no operating system. C++ offers <strong>close-to-hardware programming</strong> with the ability to write <strong>efficient, deterministic, and compact code</strong>.</p><p>— <strong>Real-World Examples:</strong><br>1. <strong>Automotive ECUs (Engine Control Units)</strong>.<br>2. <strong>Smart appliances</strong>, <strong>medical equipment</strong>, <strong>sensors</strong>, and <strong>wearables</strong>.<br>3. <strong>Arduino</strong>, <strong>Raspberry Pi</strong> (often use C++ in embedded Linux projects).</p><p>— <strong>Technical Justification:<br></strong>1. <strong>Real-time response</strong>: Software must act predictably under strict time constraints.<strong><br>2. Resource constraints</strong>: Programs must use minimal RAM and power.<br>3. <strong>Driver development</strong> and low-level protocols (SPI, I2C, UART) are commonly implemented in C++.</p><h3>4. Finance and High-Frequency Trading —</h3><p>In HFT and quantitative finance, <strong>every microsecond matters</strong>. C++ provides the speed and fine-tuned memory control needed to execute trades in milliseconds or less.</p><p>— <strong>Real-World Examples:</strong><br>1. <strong>Goldman Sachs</strong>, <strong>Morgan Stanley</strong>, <strong>Bloomberg</strong>, and <strong>Citadel</strong> all use C++ for algorithmic trading platforms.<br>2. <strong>QuantLib</strong>: A popular open-source C++ library for quantitative finance.</p><p>— <strong>Technical Justification:<br></strong>1. <strong>Low latency</strong>: C++ code can execute millions of operations in under a second.<br>2. <strong>Concurrency &amp; parallelism</strong>: Multi-threading for analyzing large datasets.<br>3. <strong>Custom memory pools</strong> to avoid latency from memory allocation.</p><h3>5. Artificial Intelligence (AI) and Machine Learning —</h3><p>While Python is dominant at the <em>interface</em> level, production environments require the <strong>speed of C++</strong> under the hood. Major AI libraries are built in C++ for computational efficiency.</p><p>— <strong>Real-World Examples:</strong><br>1. <strong>TensorFlow</strong> and <strong>PyTorch</strong> have C++ backends.<br>2. <strong>ONNX Runtime</strong>, <strong>XGBoost</strong>, and <strong>LightGBM</strong> are performance-optimized in C++.</p><p>— <strong>Technical Justification:<br></strong>1. <strong>Optimized numerical computation</strong> using BLAS, LAPACK, and SIMD instructions.<br>2. <strong>CUDA (Compute Unified Device Architecture)(for GPU acceleration)</strong>: Often integrated via C++.<br>3. <strong>Integration with embedded AI/ML models</strong> in robots, phones, and edge devices.</p><h3>6. Aerospace, Defense, and Robotics —</h3><p>Mission-critical software must be <strong>fail-safe, real-time, and highly optimized</strong>. There’s no room for sluggish performance or unpredictable garbage collection.</p><p>— <strong>Real-World Examples:</strong><br>1. <strong>NASA’s Mars rovers</strong>, <strong>drones</strong>, <strong>missile systems</strong>, and <strong>autopilot software</strong> use C++.<br>2.<strong>ROS (Robot Operating System)</strong>: Primarily written in C++.<br>3. <strong>Military-grade flight simulators</strong> and <strong>navigation systems</strong> depend on it.</p><p>— <strong>Technical Justification:<br></strong>1. <strong>Real-time constraints</strong>: Precise control over CPU cycles and memory.<br>2. <strong>Reliability</strong>: Critical for safety and control systems.<br>3. <strong>Hardware interfacing</strong>: Communicating with sensors, motors, actuators.</p><h3>Dev Tools and Compilers</h3><p>Even modern programming languages (like Rust, JavaScript engines, or Python interpreters) are <strong>compiled with C/C++</strong>.<br>- <strong>GCC</strong>, <strong>Clang</strong>, <strong>LLVM</strong>, <strong>MSVC</strong> — all major compilers are written in C++.<br>- <strong>Git</strong>, <strong>Docker (core)</strong>, and many system-level tools are C++ based.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*txV1WxT-eOIj0p6y_hMfqA.png" /></figure><p>C++ is not dying; it’s evolving. While it may not be the best fit for every problem, it is <strong>irreplaceable in domains where speed, memory, and control matter</strong>. Writing off C++ is like ignoring the foundation while admiring the structure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f894636baf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What really happen when we hit the power button of our PC ?]]></title>
            <link>https://medium.com/@pratikkatkar13/what-really-happen-when-we-hit-the-power-button-of-our-pc-3e67745e74ca?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e67745e74ca</guid>
            <category><![CDATA[booting]]></category>
            <category><![CDATA[psu-unit]]></category>
            <category><![CDATA[first-post-test]]></category>
            <category><![CDATA[bootloader]]></category>
            <category><![CDATA[boot-sequence]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 11:05:41 GMT</pubDate>
            <atom:updated>2025-06-09T11:10:56.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>What really happens when we hit the power button of our PC ?</h3><p><strong>Have you ever wondered what happens when you press the power button on your computer</strong>? It’s not just magic, it’s a carefully choreographed process involving hardware, firmware, and software working together. Let’s explore this <strong>booting process</strong> step by step — <strong>“From Power to Productivity: The hidden journey of your PC”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Lh_eK5DbIbz8qDyuo_adrA.png" /></figure><h3>1️⃣ Power Supply Initialization.</h3><ul><li>When you press the <strong>power button</strong>, the <strong>Power Supply Unit (PSU)</strong> receives electricity and performs a <strong>Power Good check</strong>.</li><li>Once voltages are stable, it sends a signal to the <strong>motherboard</strong>, waking up the CPU and other components.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*GEPB8TPvhN6JzSWNRwvPiA.png" /></figure><h3>2️⃣ CPU Fetches the Reset Vector.</h3><ul><li>After receiving power, the <strong>CPU doesn’t start with instructions</strong> from RAM or disk.</li><li>It jumps to a hardcoded memory address called the <strong>reset vector </strong>which is<strong> </strong>often pointing to BIOS/UEFI firmware stored on a ROM chip on the motherboard.</li><li>This tells the CPU where to <strong>begin execution</strong>.</li></ul><h3>3️⃣ BIOS/UEFI Firmware Begins</h3><ul><li>The CPU starts executing code from the <strong>BIOS</strong> (Basic Input/Output System) or the newer <strong>UEFI</strong> (Unified Extensible Firmware Interface).</li><li>BIOS/UEFI is responsible for initializing hardware and running <strong>POST (Power-On Self Test) — </strong>It checks if essential hardware like RAM, CPU, and GPU are present and working.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*O9AeGEN3FDyipfph1dB-Vg.png" /></figure><h4>Depending on the stage where POST fails it has specific output :</h4><ul><li><strong>No power-up at all</strong> → Likely PSU or motherboard.</li><li><strong>Beep but no display</strong> → RAM or GPU issue.</li><li><strong>POST message stuck on screen</strong> → Storage or bootloader issue.</li><li><strong>No keyboard response</strong> → Keyboard controller failure or USB issue.</li></ul><h3>4️⃣ CMOS and RTC: The Silent Helpers</h3><p>Alongside BIOS/UEFI, there’s a small <strong>coin-cell battery</strong> on your motherboard — this powers the <strong>CMOS chip</strong> and the <strong>Real-Time Clock (RTC)</strong>.</p><h4>What is CMOS?</h4><ul><li>CMOS (Complementary Metal-Oxide Semiconductor) is a memory chip that stores BIOS settings like:</li><li>System date and time</li><li>Boot sequence</li><li>CPU/RAM configs</li><li>Powered by a small battery (usually CR2032), even when the system is off.</li></ul><h4>What is RTC?</h4><ul><li>A hardware <strong>clock chip</strong> that keeps ticking 24/7.</li><li>BIOS reads the current time from RTC during boot so your system always knows the correct time — even after being off for days.</li></ul><h3>5️⃣ Boot Device Selection</h3><ul><li>Once the <strong>POST (Power-On Self-Test)</strong> completes successfully and confirms the hardware is functioning, your <strong>BIOS/UEFI firmware</strong> takes the next big step: <strong>finding a device to boot from</strong>.</li><li>This searching is based on the <strong>boot order of devices </strong>stored in CMOS which typically includes Internal SSD/HDD, USB drive, CD/DVD-ROM, Network (PXE boot). This is also called as<strong> Boot Priority,</strong> You can configure or change this boot order in the BIOS/UEFI settings.</li><li>The firmware locates the <strong>bootloader (</strong>a small program that begins loading the OS) it is generally located in -<br>1. On legacy systems having BIOS : Located in <strong>MBR</strong> (Master Boot Record) of 512 bytes on first sector of disk (ROM).<br>2. On modern systems having UEFI: Located in <strong>EFI System Partition its </strong>small FAT32 partition (100–500 MB).<br>/EFI/<br> ├── Microsoft/Boot/bootmgfw.efi ← Windows Bootloader<br> ├── ubuntu/grubx64.efi ← GRUB for Ubuntu<br> └── boot/bootx64.efi ← Default bootloader</li></ul><h3>6️⃣ Bootloader Execution</h3><ul><li>The <strong>bootloader</strong> (e.g., GRUB for Linux, Windows Boot Manager) is now loaded.<br>1. It loads the <strong>OS kernel</strong> into memory RAM.<br>2. It passes control to the kernel.</li><li>The bootloader is like a dispatcher handing over control to the operating system.</li></ul><h4>Examples of Bootloaders -</h4><p><strong>→ GRUB (Linux ) — </strong>Can boot multiple OSes, supports scripting.<br><strong>→</strong> <strong>LILO (Linux Older) —</strong> simpler bootloader (now rare).<br><strong>→</strong> <strong>Syslinux (Linux) —</strong> Lightweight for bootable USBs.<br><strong> → bootmgr (Windows) — </strong>Windows boot manager for Vista+.<br><strong>→ rEFInd (macOS/Linux) —</strong> Modern UEFI-based graphical boot menu<br><strong> →</strong> <strong>U-Boot (Embedded systems) —</strong> Bootloader for ARM &amp; IoT devices</p><h3>7️⃣ Kernel Initialization</h3><p>The <strong>OS kernel</strong> initializes core system components of system:</p><ul><li><strong>CPU scheduling</strong>: Manages which processes get to use the CPU and when, ensuring efficient multitasking.</li><li><strong>Memory management</strong>: Allocates and tracks system memory for processes to prevent conflicts and optimize performance.</li><li><strong>Device drivers</strong>: Loads specialized software that lets the OS communicate with hardware components like keyboards, disks, and GPUs.</li><li><strong>File system mounting</strong>: Connects the logical structure of storage devices to the OS so files and directories can be accessed.</li><li><strong>Init system (e.g., systemd/init/wininit)</strong>: Starts essential background services and user sessions after the kernel finishes booting.</li></ul><h3>8️⃣ User Space and GUI Start</h3><p>The init system starts essential services like:<br> 1. Network manager<br> 2. Login manager<br> 3. Background daemons<br>Then it loads the <strong>Graphical User Interface (GUI)</strong> and login screen</p><h3>9️⃣Login and Desktop Environment</h3><p>Once you log in:</p><ul><li>Your desktop environment loads.</li><li>Startup apps are launched.</li><li>You’re now in full control of the system.</li></ul><p>In essence, the journey from pressing the power button to seeing your desktop is a orchestrated sequence involving hardware checks, firmware logic, bootloaders, and kernel execution. Each component right from CMOS storing settings, to POST validating hardware, to the bootloader dispatching the OS , plays a vital role in ensuring a seamless start. Understanding this process not only deepens your appreciation for the complexity behind everyday computing but also equips you to better diagnose issues when things go wrong. The next time your PC boots up, you’ll know the silent symphony happening beneath the surface.</p><p><strong>Power Button → PSU → CPU Reset Vector → BIOS/UEFI → CMOS/RTC → POST → Boot Device → Bootloader → Kernel → Init System → GUI/Login → Desktop.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e67745e74ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Static Keyword in C++: From Basics to Advanced]]></title>
            <link>https://medium.com/@pratikkatkar13/mastering-static-keyword-in-c-from-basics-to-advanced-4bc9107eb80d?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc9107eb80d</guid>
            <category><![CDATA[singleton-class]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[static-function]]></category>
            <category><![CDATA[static-keyword]]></category>
            <category><![CDATA[static-member]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 03:32:29 GMT</pubDate>
            <atom:updated>2025-06-01T05:51:39.939Z</atom:updated>
            <content:encoded><![CDATA[<p>The static keyword in C++ is a powerful feature that plays different roles depending on its context. Understanding static is crucial for writing optimized, safe, and modular C++ code. static specifies that a symbol has <strong>static storage duration, </strong>meaning that its lifetime lasts throughout the program’s execution. In this blog, we’ll walk through every use-case of the static keyword, from simple applications to more advanced scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYy9gko0U6xfsd50VAgpzg.png" /></figure><h3>1. Static Variables in Functions (Local Scope)</h3><p>A static variable inside a function retains its value between multiple function calls. Unlike regular local variables, it is initialized only once and exists for the lifetime of the program.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void counter() {<br>    static int count = 0;  // initialized only once its value is preserved between function calls.<br>    count++;<br>    cout &lt;&lt; &quot;Count: &quot; &lt;&lt; count &lt;&lt; endl;<br>}<br>void counter1() {<br>   int count1 = 0;  // initialized for every function calling.<br>    count1++;<br>    cout &lt;&lt; &quot;Count1: &quot; &lt;&lt; count1 &lt;&lt; endl;<br>}<br><br>int main() {<br>    counter();   // Count: 1<br>    counter();   // Count: 2<br>    counter();   // Count: 3<br><br>    counter1();  // Count: 1<br>    counter1();  // Count: 1<br>    counter1();  // Count: 1<br>    return 0;<br>}</pre><h3>2. Static Variables in Global Scope (Internal Linkage)</h3><p>When you declare a global variable as static, it has <strong>internal linkage</strong>, meaning it is <strong>not visible</strong> outside the file it is declared in. If at all you want to access the static variable declared in file1.cpp to file2.cpp then you should declared getter() and setter() for variable in file1.cpp and link them to file2.cpp as getter() and setter() will not be static functions. Generally it is used to to restrict access to global variables or functions within a translation unit (file).</p><pre>// file1.cpp<br>static int id = 100;  // only accessible within file1.cpp<br><br>// file2.cpp<br>extern int id;  // This will cause a linker error because `id` is not visible here</pre><h3>3. Static Variables in Namespaces (File Scope)</h3><p>A static variable inside a namespace behaves similarly to one in the global scope—it gets <strong>internal linkage</strong>, meaning it won’t be accessible in other translation units (files).</p><pre>// file1.cpp<br>#include &lt;iostream&gt;<br>using namespace std;<br>namespace MyNamespace {<br>    static int counter = 42; // Internal linkage - only visible in file1.cpp<br>  }  <br><br>int main() {<br>    cout &lt;&lt; &quot;Counter in file1: &quot; &lt;&lt; MyNamespace::counter &lt;&lt; endl; // 42<br>    return 0;<br>}<br><br><br>// file2.cpp<br>#include &lt;iostream&gt;<br>using namespace std;<br>// extern int MyNamespace::counter;  -- This will cause a linker error!<br><br>int main() {<br>    // cout &lt;&lt; &quot;Counter in file2: &quot; &lt;&lt; MyNamespace::counter &lt;&lt; endl; <br>    return 0;<br>}</pre><h3>4. Static Data Members in Classes</h3><p>A static member variable belongs to the <strong>class</strong>, not to any particular object. There is only <strong>one copy</strong> of the static member, shared by all objects. Static data members needs <strong>definition outside</strong> the class and can be accessed without object as it is object independent (Classname :: variablename).</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Student {<br>public:<br>    static int totalStudents;<br><br>    Student() {<br>        totalStudents++;<br>    }<br>};<br><br>int Student::totalStudents = 0;  // Definition outside the class<br><br>int main() {<br>    Student s1, <br>    Student s2,<br>    Student s3,<br>    cout &lt;&lt; &quot;Total Students: &quot; &lt;&lt; Student::totalStudents &lt;&lt; endl; // Output: 3<br>    return 0;<br>}</pre><h3>5. Static Member Functions in Classes</h3><p>A <strong>static member function</strong>:</p><ul><li>Belongs to the <strong>class</strong>, not to any object.</li><li>Can be called using the class name directly (Classname :: Function_name() ).</li><li>Cannot access <strong>non-static members</strong> (variables or functions) of the class.</li><li>Cannot use the this pointer, because it’s not tied to any instance.</li></ul><p>Static member functions are used to <strong>encapsulate logic</strong> that belongs to the class itself and not to any object, <strong>organize utility methods </strong>and<strong> avoid unnecessary object creation</strong> for stateless logic.</p><pre>class Math {<br>public:<br>    static int square(int x) {<br>        return x * x;<br>    }<br>};<br><br>int main() {<br>    cout &lt;&lt; &quot;Square: &quot; &lt;&lt; Math::square(5) &lt;&lt; endl;  // Output: 25<br>}</pre><pre>// Static Method with Static Variable<br>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Counter {<br>private:<br>    static int count;<br><br>public:<br>    static void increment() { // Static Method<br>        count++;<br>    }<br><br>    static void showCount() { // Static Method<br>        cout &lt;&lt; &quot;Count: &quot; &lt;&lt; count &lt;&lt; endl;<br>    }<br>};<br><br>int Counter::count = 0;  // Static member variable must be defined outside<br><br>int main() {<br>    Counter::increment();  // count = 1<br>    Counter::increment();  // count = 2<br>    Counter::showCount();  // Output: Count: 2<br>    return 0;<br>}</pre><h3>6. Static Classes or Nested Static Classes</h3><p><strong>C++ does not allow Static classes in the same way.</strong> There&#39;s no syntax like static class MyClass {}.<br>In C++, you <strong>emulate</strong> a static class by</p><ul><li>Creating a normal class</li><li><strong>Class has only static data members</strong></li><li><strong>Class has only static member function</strong></li><li><strong>Deleting or privatizing the constructor</strong> to prevent instantiation of class.</li></ul><pre>#include &lt;iostream&gt;<br>using namespace std;<br>class MathUtils {<br>private:<br>    MathUtils() = delete;  // Prevent instantiation<br> <br>public:<br>    static int a = 10; <br><br>    static int add(int a, int b) { // static member function<br>        return a + b;<br>    }<br><br>    static int square(int x) { // static member function<br>        return x * x;<br>    }<br>};<br><br>int MathUtils::a = 14; // Definition outside the class<br><br><br>int main() {<br>    // MathUtils obj;   Error: constructor is deleted<br>    cout &lt;&lt; &quot;a: &quot; &lt;&lt; MathUtils::a &lt;&lt; endl; // Output -  a: 14<br>    cout &lt;&lt; &quot;Add: &quot; &lt;&lt; MathUtils::add(5, 3) &lt;&lt; endl; // Output -  Add: 8<br>    cout &lt;&lt; &quot;Square: &quot; &lt;&lt; MathUtils::square(4) &lt;&lt; endl; // Output - Square: 16<br>    return 0;<br>}</pre><p>C++ also doesn’t support <strong>declaring a nested class as </strong><strong>static</strong> explicitly, but you can simulate it:</p><ul><li>A <strong>nested class</strong> does <strong>not</strong> have an implicit reference to the outer class.</li><li>So, it behaves <strong>like a static class</strong>: no access to non-static outer members.</li></ul><pre>#include &lt;iostream&gt;<br><br>class Outer {<br>public:<br>    class Inner {<br>    public:<br>        static void greet() {<br>            std::cout &lt;&lt; &quot;Hello from Inner class!&quot; &lt;&lt; std::endl;<br>        }<br>    };<br>};<br><br>int main() {<br>    Outer::Inner::greet();  // No Outer object needed<br>    return 0;<br>}</pre><p>Here, Inner behaves like a static class because:</p><ul><li>It doesn’t rely on an Outer object.</li><li>Its methods are static.</li><li>There’s no this pointer from Outer.</li></ul><h3>7. Use of Static for Singleton Design Pattern</h3><p>The static keyword is central to implementing the <strong>singleton</strong> pattern in C++.</p><p>A <strong>Singleton class</strong> is a design pattern that ensures a <strong>class has only one instance</strong> throughout the program’s lifetime and provides a <strong>global point of access</strong> to that instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*rHpRBoNEfzxnz5wrIIgJjA.png" /></figure><ol><li><strong>Private Constructor</strong><br> Prevents direct creation of objects from outside the class.</li><li><strong>Static Instance Pointer</strong><br> Holds the sole instance of the class.</li><li><strong>Public Static Method (</strong><strong>getInstance())</strong><br> Provides controlled access to the single instance. It creates the instance on the first call (lazy initialization)</li><li><strong>Deleted Copy Constructor and Assignment Operator</strong><br> Prevents copying or assigning the Singleton, maintaining its uniqueness.</li></ol><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Singleton {<br>private:<br>    // Static pointer to hold the single instance<br>    static Singleton* instance;<br><br>    // Private constructor to prevent instantiation<br>    Singleton() {<br>        cout &lt;&lt; &quot;Singleton Constructor Called\n&quot;;<br>    }<br><br>    // Delete copy constructor and assignment operator<br>    Singleton(const Singleton&amp;) = delete;<br>    Singleton&amp; operator=(const Singleton&amp;) = delete;<br><br>public:<br>    // Static method to provide access to the instance<br>    static Singleton* getInstance() {<br>        if (!instance) {<br>            instance = new Singleton();  // Lazy initialization<br>        }<br>        return instance;<br>    }<br><br>    // Example method<br>    void showMessage() {<br>        cout &lt;&lt; &quot;Hello from Singleton instance!\n&quot;;<br>    }<br>};<br><br>// Initialize static member<br>Singleton* Singleton::instance = nullptr;<br><br>// Test in main<br>int main() {<br>    Singleton* s1 = Singleton::getInstance();<br>    Singleton* s2 = Singleton::getInstance();<br><br>    s1-&gt;showMessage();<br><br>    // Show that both pointers point to the same instance<br>    cout &lt;&lt; &quot;s1 address: &quot; &lt;&lt; s1 &lt;&lt; endl;<br>    cout &lt;&lt; &quot;s2 address: &quot; &lt;&lt; s2 &lt;&lt; endl;<br><br>    return 0;<br>}<br><br>// output -<br>// Singleton Constructor Called<br>// Hello from Singleton instance!<br>// s1 address: 0x5611d4fece70<br>// s2 address: 0x5611d4fece70</pre><h3>Guess the answer —</h3><h4>1. Where should a static class member variable be defined?</h4><p>A. Inside the constructor<br> B. Inside the class definition<br> C. Outside the class definition<br> D. In the destructor</p><h4>2. Which of the following is true about static member variables?</h4><p>A. They are specific to each object<br> B. They are shared among all instances of the class<br> C. They can only be used within the constructor<br> D. They are initialized in the constructor</p><h4>3. Choose the correct syntax to access a static member function.</h4><p>A. obj.function()<br>B. this-&gt;function()<br>C. ClassName::function()<br>D. function()</p><h4>4. Can a static function inside a class access the this pointer?</h4><p>A. Yes, always<br> B. No<br> C. Only in certain cases<br> D. Only if it’s friend function</p><h4>Answers-</h4><p>1- C. Outside the class definition<br>2- B. They are shared among all instances of the class<br>3- C. ClassName::function()<br>4- B. No</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc9107eb80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Macros and Inline in C++.]]></title>
            <link>https://medium.com/@pratikkatkar13/demystifying-macros-and-inline-in-c-28e6686e5e36?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e6686e5e36</guid>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[macros-type]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[inline-vs-macros]]></category>
            <category><![CDATA[inline-functions]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Sun, 25 May 2025 10:19:50 GMT</pubDate>
            <atom:updated>2025-05-25T10:19:50.423Z</atom:updated>
            <content:encoded><![CDATA[<h3>Macros</h3><p>In C++, <strong>macros</strong> are a feature of the <strong>C preprocessor , </strong>a tool that runs before the actual compilation of code. Macros allow you to define <strong>symbolic constants</strong>, <strong>inline functions</strong>, and perform <strong>conditional compilation</strong>. While they’re powerful, they must be used with care due to some inherent risks.</p><p>A <strong>macro</strong> is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. Macros are defined using the <strong>#define</strong> directive.</p><h3>Advantages of Macros</h3><ol><li><strong>Performance</strong>: Inline substitution reduces function call overhead.</li><li><strong>Code Readability</strong>: Helps avoid hard-coded values (e.g., #define PI 3.14).</li><li><strong>Conditional Compilation</strong>: Allows compiling code selectively based on platform/debug needs.</li><li><strong>No Type Checking</strong>: Works with any data type.</li></ol><h3>Types of Macros —</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*4mvpoH7WrZQ42VMM6HtNXg.png" /></figure><h4>1. Object-like Macros —</h4><p>These are the simplest form used for constant replacement.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define PI 3.14159  // Object-like macro<br><br>int main() {<br>    cout &lt;&lt; &quot;Value of PI: &quot; &lt;&lt; PI &lt;&lt; endl;<br>    return 0;<br>}<br><br>// Output - Value of PI: 3.14159</pre><h4>2. Function-like Macros —</h4><p>These resemble functions but are expanded inline. Always use parentheses around arguments to avoid operator precedence issues.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define SQUARE(x) ((x) * (x))  // Function-like macro<br><br>int main() {<br>    int num = 5;<br>    cout &lt;&lt; &quot;Square of &quot; &lt;&lt; num &lt;&lt; &quot; is: &quot; &lt;&lt; SQUARE(num) &lt;&lt; endl;<br>    return 0;<br>}<br><br>// Output - Square of 5 is: 25</pre><h4>3. <strong>Chain Macro —</strong></h4><p>One macro can invoke another macro in macro definition.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define PI 3.14159<br>#define RADIUS 10<br>#define AREA_CIRCLE (PI * RADIUS * RADIUS)  // Chain macro<br><br>int main() {<br>    cout &lt;&lt; &quot;Area of Circle (radius = &quot; &lt;&lt; RADIUS &lt;&lt; &quot;): &quot; &lt;&lt; AREA_CIRCLE &lt;&lt; endl;<br>    return 0;<br>}<br><br>// Output - Area of Circle (radius= 10): 314.159</pre><h4>4. Multiline Macros —</h4><p>Using backslash \ to continue macros on multiple lines.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define PRINT_DETAILS(name, age) \<br>    cout &lt;&lt; &quot;Name: &quot; &lt;&lt; name &lt;&lt; endl; \<br>    cout &lt;&lt; &quot;Age: &quot; &lt;&lt; age &lt;&lt; endl;  // Multiline macro<br><br>int main() {<br>    PRINT_DETAILS(&quot;Alice&quot;, 30);<br>    return 0;<br>}<br><br>// Output - Name : Alice<br>//          Age : 30         </pre><h4>5. <strong>Parameterized Macro —</strong></h4><p>These accept arguments like functions:</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define MAX(a, b) ((a) &gt; (b) ? (a) : (b))  // Parameterized macro<br><br>int main() {<br>    int a = 15, b = 20;<br>    cout &lt;&lt; &quot;Max of &quot; &lt;&lt; a &lt;&lt; &quot; and &quot; &lt;&lt; b &lt;&lt; &quot; is: &quot; &lt;&lt; MAX(a, b) &lt;&lt; endl;<br>    return 0;<br>}<br><br>// Output - Max of 15 and 20 is: 20</pre><h4>6. Conditional Compilation Macros —</h4><p>These help control compilation based on conditions.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define DEBUG  // Define DEBUG for conditional compilation<br><br>#ifdef DEBUG<br>    #define LOG(msg) cout &lt;&lt; &quot;[DEBUG] &quot; &lt;&lt; msg &lt;&lt; endl;<br>#else<br>    #define LOG(msg)<br>#endif<br><br>int main() {<br>    LOG(&quot;This message is shown only in DEBUG mode&quot;);<br>    return 0;<br>}<br><br>// Output - [DEBUG] This message is shown only in DEBUG mode</pre><p>This line defines a macro named <strong>DEBUG.</strong> It’s like telling the preprocessor: “DEBUG mode is ON.” It’s not a variable or a constant — it’s just a flag for the <strong>preprocessor</strong>.</p><ul><li>#ifdef DEBUG: Checks <strong>if</strong> the DEBUG macro is defined.</li><li>If DEBUG <em>is</em> defined:</li><li>The macro LOG(msg) is defined to print the message with a [DEBUG] tag.</li><li>If DEBUG <em>is not</em> defined:</li><li>The macro LOG(msg) does <strong>nothing</strong> (i.e., it&#39;s replaced by nothing).</li></ul><p>This allows you to <strong>easily enable or disable debugging messages</strong> by commenting/uncommenting #define DEBUG.</p><h3>Disadvantages of Macros</h3><ol><li><strong>No Type Safety</strong>: Compiler does not check the types.</li><li><strong>Debugging Difficulty</strong>: Errors in macro expansions are hard to trace.</li><li><strong>Code Bloat</strong>: Every use of a macro expands code, unlike inline function</li><li><strong>Unexpected Behavior</strong>: Can lead to logical bugs if not parenthesized properly.</li></ol><p><strong>It is always better to use Inline function when we have calculations , prefer type safe performance, want more code readability and prefer code error checking at compile time</strong>.</p><h3>Inline Function —</h3><p>An <strong>inline function</strong> is a function where the <strong>compiler attempts to replace the function call with the actual code of the function</strong>, reducing the overhead of function calls. The inline keyword <strong>suggests</strong> to the compiler to expand the function code <strong>in place</strong> at compile time. It’s a <strong>request</strong>, not a command — the compiler may ignore it.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>inline int square(int x) {<br>    return x * x;<br>}<br><br>int main() {<br>    cout &lt;&lt; &quot;Square of 5 is: &quot; &lt;&lt; square(5) &lt;&lt; endl;<br>    return 0;<br>}<br><br>// Output - Square of 5 is: 25</pre><p><strong>A function defined in class is always an inline function.</strong></p><pre>class A {<br>public:<br>    int square(int x) { return x * x; }  // implicitly inline<br>};</pre><h4>Advantages of Inline Functions —</h4><ol><li><strong>Eliminates Function Call Overhead (</strong>No pushing/popping of stack frames)</li><li><strong>Speeds Up Small, Frequently Used Function (</strong>Ideal for simple functions like max, min, square, etc.<strong>)</strong></li><li><strong>Supports Type Safety (</strong>Unlike macros, inline functions are <strong>type-checked</strong> by the compiler.<strong>)</strong></li><li><strong>Safe Argument Evaluation (</strong>Each argument is <strong>evaluated once</strong> (unlike macros)</li></ol><h4>When Not to Use —</h4><p><strong>1. Code Bloat (larger binary size)</strong></p><p><strong>2. Not Suitable for Large Functions</strong></p><p><strong>3. Cannot Always Be Inlined ( Function containing Loops, Recursion, Switch Case, Complex logic)</strong></p><p><strong>4. Less Useful in Modern CPUs (</strong>Function calls are fast; inlining offers less benefit today.<strong>)</strong></p><h3>Inline vs Macros-</h3><h4>1. Evaluation Risk —</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>// Macro definition<br>#define SQUARE(x) ((x) * (x))<br><br>// Inline function definition<br>inline int square(int x) {<br>    return x * x;<br>}<br><br>int main() {<br>    int a = 5;<br>    int b = 5;<br><br>    // Using macro<br>    int result_macro = SQUARE(a++);  // Expands to ((a++) * (a++)) <br>    cout &lt;&lt; &quot;Result using macro: &quot; &lt;&lt; result_macro &lt;&lt; &quot;, a after macro: &quot; &lt;&lt; a &lt;&lt; endl;<br><br>    // Using inline function<br>    int result_inline = square(b++);  // b++ evaluated once <br>    cout &lt;&lt; &quot;Result using inline function: &quot; &lt;&lt; result_inline &lt;&lt; &quot;, b after inline: &quot; &lt;&lt; b &lt;&lt; endl;<br><br>    return 0;<br>}<br><br>// Output - <br>// Result using macro: 30, a after macro: 7<br>// Result using inline function: 25, b after inline: 6</pre><ul><li>The <strong>macro evaluates </strong><strong>a++ twice</strong>, causing unexpected behavior (value changes more than once and may result in incorrect result or <strong>undefined behavior</strong>).</li><li>The <strong>inline function evaluates </strong><strong>b++ only once</strong>, giving the correct and predictable result.</li><li>Remember its an <strong>post increment</strong> so values will be first used then incremented</li></ul><h4>2. Readability —</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define DOUBLE(x) (2 * x)<br>inline int TRIPLE(int x) { return 2 * x; }<br><br>int main() {<br>    cout &lt;&lt; DOUBLE(10 + 10) &lt;&lt; endl; // 2 * 10 + 10 = 20 + 10 = 30<br>    cout &lt;&lt; TRIPLE(10 + 10) &lt;&lt; endl; // 2 * 20 = 40<br>    return 0;<br>}<br><br>// output - <br>// 30<br>// 40</pre><p><strong>Macros</strong> perform <strong>textual substitution</strong> before compilation.</p><ul><li>DOUBLE(10 + 10) becomes 2 * 10 + 10 → evaluates to <strong>30</strong>, not <strong>40</strong>. In order to make it 40 macros should be <strong>#define DOUBLE(x) (2 * (x))</strong>.</li><li>Macros are error-prone if not written with proper parentheses.</li></ul><p><strong>Inline functions</strong> are <strong>type-safe and context-aware</strong>.</p><ul><li>TRIPLE(10 + 10) properly passes 20 to the function → evaluates to <strong>60</strong>.</li><li>Safer and more reliable for expression evaluation.</li></ul><h4>3. Type checking —</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>// Macro: No type checking<br>#define ADD(x, y) ((x) + (y))<br><br>// Inline function: Type-checked<br>inline int add(int x, int y) {<br>    return x + y;<br>}<br><br>int main() {<br>    // Using macro – allows mismatched types<br>    cout &lt;&lt; &quot;Macro result: &quot; &lt;&lt; ADD(&quot;Hello&quot;, 5) &lt;&lt; endl;  // Compiles, but wrong logic<br><br>    // Using inline function – causes compile-time error<br>    // cout &lt;&lt; &quot;Inline result: &quot; &lt;&lt; add(&quot;Hello&quot;, 5) &lt;&lt; endl; <br><br>    return 0;<br>}</pre><ul><li>The macro ADD(&quot;Hello&quot;, 5) compiles, but it does pointer arithmetic (&quot;Hello&quot; + 5), which gives garbage or crashes.</li><li>The inline function add(&quot;Hello&quot;, 5) gives a <strong>compile-time error</strong>, preventing misuse.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*mJc8McbQv2KmbGW-_A6syg.png" /></figure><h3>Example for practice , guess the output !!</h3><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>#define CL 10 + 1<br>const int C2 = 10;<br><br>int main() {<br>    int n1, n2;<br>    n1 = CL * 100 * C2;<br>    n2 = C2 * 100 * CL;<br>    cout &lt;&lt; n1 &lt;&lt; &quot; &quot; &lt;&lt; n2;<br>    return 0;<br>}<br><br>// Output - 1010 10001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*YVo4PMM284dHma8BC6MeyA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e6686e5e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced points on Constructors and Destructors in C++ calling order……]]></title>
            <link>https://medium.com/@pratikkatkar13/advanced-points-on-constructors-and-destructors-in-c-calling-order-c9d06b3c0bcb?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d06b3c0bcb</guid>
            <category><![CDATA[default-keyword]]></category>
            <category><![CDATA[delete-keyword]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[constructor]]></category>
            <category><![CDATA[destructor]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Mon, 19 May 2025 08:41:23 GMT</pubDate>
            <atom:updated>2025-05-19T08:41:23.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*d77ryf4DCEkq99wuMvi1qQ.png" /></figure><p>We all know what is constructor and destructors, basically the need of constructor is it allows object to be initialized <strong>automatically</strong> when they are created and <strong>Without a constructor</strong>, you’d have to write multiple lines just to initialize each object manually. With constructor you can define <strong>multiple constructors</strong> (constructor overloading) to give flexibility in how an object is created.</p><pre>class Person {<br>public:<br>    string name;<br>    int age;<br><br>    // Constructor 1<br>    Person(string n, int a) {<br>        name = n;<br>        age = a;<br>    }<br>    <br>    // Constructor 1<br>    Person(string n) {<br>        name = n;<br>    }<br>};<br>int main() {<br><br>    //  by default c++ custom class has an construtor if not defined but <br>    //  if defined then default one is overloads by defined one.<br>  <br>    Person p(&quot;Alice&quot;, 25);  // Constructor1 is called automatically<br>    //  no need to have p.name = &quot;Alice&quot;, p.age = &quot;25&quot;<br><br>    Person p1(&quot;bob&quot;);  // Constructor2 is called automatically<br>    p1.age = 26;<br>}</pre><h3>1. Order in which constructors and destructors is called in inheritance.</h3><p>Always the constructors are called from left to right in order they are inherited by derived class and then derived class constructor is called. The order of destructor is reversed the order of constructors called.</p><h4>Rule:</h4><ul><li><strong>Constructors</strong> are called <strong>base to derived</strong>.</li><li><strong>Destructors</strong> are called <strong>derived to base</strong>.</li></ul><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    Base() { cout &lt;&lt; &quot;Base Constructor\n&quot;; }<br>    ~Base() { cout &lt;&lt; &quot;Base Destructor\n&quot;; }<br>};<br><br>class Derived : public Base {<br>public:<br>    Derived() { cout &lt;&lt; &quot;Derived Constructor\n&quot;; }<br>    ~Derived() { cout &lt;&lt; &quot;Derived Destructor\n&quot;; }<br>};<br><br>int main() {<br>    Derived obj; // or Derived* obj = new Derived(); and delete obj; will also have same output.<br>    return 0;<br>}<br><br> // Output - Base Constructor<br> //          Derived Constructor<br> //          Derived Destructor<br> //          Base Destructor</pre><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class A {<br>public:<br>    A() { cout &lt;&lt; &quot;Constructor A\n&quot;; }<br>    ~A() { cout &lt;&lt; &quot;Destructor A\n&quot;; }<br>};<br><br>class B : public A {<br>public:<br>    B() { cout &lt;&lt; &quot;Constructor B\n&quot;; }<br>    ~B() { cout &lt;&lt; &quot;Destructor B\n&quot;; }<br>};<br><br>class C :public A{<br>public:<br>    C() { cout &lt;&lt; &quot;Constructor C\n&quot;; }<br>    ~C() { cout &lt;&lt; &quot;Destructor C\n&quot;; }<br>};<br><br>class D : public B, public C{<br>public:<br>    D() { cout &lt;&lt; &quot;Constructor D\n&quot;; }<br>    ~D() { cout &lt;&lt; &quot;Destructor D\n&quot;; }<br>};<br><br>int main() {<br>    D obj;  // Non-polymorphic object<br>    return 0;<br>}<br><br>// output:-<br>// Constructor A<br>// Constructor B<br>// Constructor A<br>// Constructor C<br>// Constructor D<br>// Destructor D<br>// Destructor C<br>// Destructor A<br>// Destructor B<br>// Destructor A</pre><p>To void this “constructor A” calling again and again we can inherit class A <strong>virtually</strong> in class ‘B’ and class ‘C’, so each time Object ‘A’ is not created, once created then shared by all derived class provided the derived class inherits class ‘A’ virtually.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class A {<br>public:<br>    A() { cout &lt;&lt; &quot;Constructor A\n&quot;; }<br>    ~A() { cout &lt;&lt; &quot;Destructor A\n&quot;; }<br>};<br><br>class B : virtual  public A { // class A inherited virtually <br>public:<br>    B() { cout &lt;&lt; &quot;Constructor B\n&quot;; }<br>    ~B() { cout &lt;&lt; &quot;Destructor B\n&quot;; }<br>};<br><br>class C : virtual public A { // Class A inherited virtually <br>public:<br>    C() { cout &lt;&lt; &quot;Constructor C\n&quot;; }<br>    ~C() { cout &lt;&lt; &quot;Destructor C\n&quot;; }<br>};<br><br>class D : public B, public C {<br>public:<br>    D() { cout &lt;&lt; &quot;Constructor D\n&quot;; }<br>    ~D() { cout &lt;&lt; &quot;Destructor D\n&quot;; }<br>};<br><br>int main() {<br>    D obj;  // Non-polymorphic object<br>    return 0;<br>}<br><br>// output:-<br>// Constructor A<br>// Constructor B<br>// Constructor C<br>// Constructor D<br>// Destructor D<br>// Destructor C<br>// Destructor B<br>// Destructor A</pre><h3>2. Order in which constructors and destructors is called in polymorphic or dynamic memory allocation.</h3><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    Base() { cout &lt;&lt; &quot;Base Constructor\n&quot;; }<br>    ~Base() { cout &lt;&lt; &quot;Base Destructor\n&quot;; }<br>};<br><br>class Derived : public Base {<br>public:<br>    Derived() { cout &lt;&lt; &quot;Derived Constructor\n&quot;; }<br>    ~Derived() { cout &lt;&lt; &quot;Derived Destructor\n&quot;; }<br>};<br><br>int main() {<br>    Base* ptr = new Derived();  // Polymorphic allocation<br>    delete ptr;                 // Destructor called via base pointer<br>    return 0;<br>}<br><br>// output - <br>// Base Constructor<br>// Derived Constructor<br>// Base Destructor</pre><p>In the above code the derived class object address is stored in base class pointer and we know in this case the base pointer “ptr” will call all the base class method and can call the derived class method if it is redefined in derived class and virtual in base call (run time polymorphism). Hence once the base class “ptr” is deleted then it has nothing to do with derived class so derived class destructor is not called. In order to make the derived class destructor call we should make base class constructor virtual.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    Base() { cout &lt;&lt; &quot;Base Constructor\n&quot;; }<br>    virtual ~Base() { cout &lt;&lt; &quot;Base Destructor\n&quot;; } //base class virtual destructor<br>};<br><br>class Derived : public Base {<br>public:<br>    Derived() { cout &lt;&lt; &quot;Derived Constructor\n&quot;; }<br>    ~Derived() { cout &lt;&lt; &quot;Derived Destructor\n&quot;; }<br>};<br><br>int main() {<br>    Base* ptr = new Derived();  // Polymorphic allocation<br>    delete ptr;                 // Destructor called via base pointer<br>    return 0;<br>}<br><br>// output - <br>// Base Constructor<br>// Derived Constructor<br>// Derived Destructor<br>// Base Destructor</pre><ul><li>The pointer ptr is of type Base*, but it actually points to a Derived object.</li><li>If the destructor in Base is <strong>not virtual</strong>, only Base::~Base() will be called — the derived part is <strong>skipped</strong>, which can cause <strong>resource leaks</strong>.</li><li>If the destructor <strong>is virtual</strong>, the destructor call is <strong>resolved dynamically at runtime</strong> — ensuring that Derived::~Derived() is called first, then Base::~Base().</li></ul><h3>3. Data Members initialization in constructor depends upon the order in which they are declared not in order they are initialize within constructor.</h3><p><strong>Example 2 —</strong></p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br>using namespace std;<br><br>class Stationery {<br>    const char *pen, *paper, *ink;  // Declared in this order<br>public:<br>    Stationery(const char* _pen, const char* _paper, const char* _ink) :<br>        pen(setPen(_pen)), paper(setPaper(_paper)), ink(setInk(_ink)) {} // initialization order<br><br>    const char* setPen(const char* item) {<br>        cout &lt;&lt; &quot;pen = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br><br>    const char* setPaper(const char* item) {<br>        cout &lt;&lt; &quot;paper = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br><br>    const char* setInk(const char* item) {<br>        cout &lt;&lt; &quot;ink = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br>};<br><br>int main() {<br>    Stationery obj(&quot;Blue Pen&quot;, &quot;A4 Sheet&quot;, &quot;Black Ink&quot;);<br>    return 0;<br>}<br><br><br>// Output - <br>// pen = Blue Pen<br>// paper = A4 Sheet<br>// ink = Black Ink</pre><p>Here we declared data member in order as <strong>pen -&gt; paper -&gt; ink</strong> so irrespective of initialization order of pen, paper and book in constructor — Stationery() the set functions are called with respect to the order of declaration only not initialization that is <strong>setPen() -&gt; setPaper() -&gt; setInk()</strong>. In the below code the declaration order is changed as <strong>pen -&gt; ink-&gt; paper</strong> and it changes the set function calling order as <strong>setPen() -&gt; setInk() -&gt; setPaper() </strong>although the order of initialization in constructor is same.</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br>using namespace std;<br><br>class Stationery {<br>    const char *pen, *ink, *paper;  // Declared in this order - changed <br>public:<br>    Stationery(const char* _pen, const char* _paper, const char* _ink) :<br>        pen(setPen(_pen)), paper(setPaper(_paper)), ink(setInk(_ink)) {} // initialization order is same or can write it in any order does not matter <br><br>    const char* setPen(const char* item) {<br>        cout &lt;&lt; &quot;pen = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br><br>    const char* setPaper(const char* item) {<br>        cout &lt;&lt; &quot;paper = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br><br>    const char* setInk(const char* item) {<br>        cout &lt;&lt; &quot;ink = &quot;&lt;&lt; item &lt;&lt; endl;<br>        return strdup(item);<br>    }<br>};<br><br>int main() {<br>    Stationery obj(&quot;Blue Pen&quot;, &quot;A4 Sheet&quot;, &quot;Black Ink&quot;);<br>    return 0;<br>}<br><br>// output - <br>// pen = Blue Pen<br>// ink = Black Ink<br>// paper = A4 Sheet</pre><p><strong>Example 2 —</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class A {<br>public:<br>    A() { cout &lt;&lt; &quot;A constructor\n&quot;; }<br>    ~A() { cout &lt;&lt; &quot;A destructor\n&quot;; }<br>};<br><br>class B {<br>public:<br>    B() { cout &lt;&lt; &quot;B constructor\n&quot;; }<br>    ~B() { cout &lt;&lt; &quot;B destructor\n&quot;; }<br>};<br><br>class P {<br>public:<br>    // order of declaring the data memebers od class P - it matters a lot.<br>    B b;<br>    A a;<br>  <br>    //  order in which constructor P initializes Data members - does not matter.<br>    P() : a(), b() { <br>        cout &lt;&lt; &quot;P constructor\n&quot;; <br>    }<br><br>    ~P() { <br>        cout &lt;&lt; &quot;P destructor\n&quot;; <br>    }<br>};<br><br>int main() {<br>    P p;<br>    return 0;<br>}<br><br>// output -  Take a moment to analyze the output based on concept of previous example<br>// B constructor<br>// A constructor<br>// P constructor<br>// P destructor<br>// A destructor<br>// B destructor</pre><h3>4. Default and Delete keywords for constructor.</h3><p>In <strong>C++11 and later</strong>, the default and delete keywords are used to explicitly control the <strong>special member functions</strong> (constructors, destructors, assignment operators, etc.) of a class.</p><p><strong>Default — </strong>Tells the compiler to <strong>generate the default implementation</strong> of a special member function, even if you’ve declared others, especially for constructors.</p><p><strong>Delete —</strong> Tells the compiler to <strong>disable</strong> or <strong>prohibit</strong> the use of a function. This is used to <strong>prevent specific operations</strong>, like copying, moving, or calling a function with certain parameters, especially for constructors.</p><p>Both = default and = delete <strong>replace a function body</strong>, and <strong>you can&#39;t use them with a function body</strong> at the same time.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Sample {<br>public:<br>    // Default constructor is explicitly allowed because down we declare <br>    // custom constructor which overloads default constructor to avoid this we use default keyword<br>    Sample() = default; <br>    // we can also have above sample() as given below - But you cannot combine &#39;= default&#39; with a function body. <br>    // Sample() {<br>    //    cout &lt;&lt; &quot;Default constructor called\n&quot;;<br>    //     } <br><br>    // Parameterized constructor - <br>    Sample(int val) {<br>        cout &lt;&lt; &quot;Parameterized constructor: &quot; &lt;&lt; val &lt;&lt; endl;<br>    }<br><br>    // Copy constructor is disabled (deleted)<br>    Sample(const Sample&amp;) = delete;<br>    // Error code - you cannot combine &#39;= delete&#39; with a function body.<br>    // Sample(const Sample&amp;) = delete {<br>    //    cout&lt;&lt; copy construtor called &lt;&lt; endl;<br>    //      }<br><br>    // Copy assignment operator is also disabled<br>    Sample&amp; operator=(const Sample&amp;) = delete;<br><br>    // Destructor<br>    ~Sample() {<br>        cout &lt;&lt; &quot;Destructor called\n&quot;;<br>    }<br>};<br><br>int main() {<br>    Sample s1;             // OK: Default constructor as we made it default by adding default keyword <br>    Sample s2(42);         // OK: Parameterized constructor<br><br>    // Sample s3 = s2;     // Error: Copy constructor is deleted<br>    // s1 = s2;            // Error: Copy assignment is deleted<br><br>    return 0;<br>}<br><br>// output - <br>// Parameterized constructor: 42<br>// Destructor called</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d06b3c0bcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced C++ (Part 1) — Demystifying shared_ptr, unique_ptr, and weak_ptr in C++]]></title>
            <link>https://medium.com/@pratikkatkar13/demystifying-shared-ptr-unique-ptr-and-weak-ptr-in-c-e7b79a1ac266?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b79a1ac266</guid>
            <category><![CDATA[shared-pointer]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[weak-pointer]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Sun, 11 May 2025 10:30:45 GMT</pubDate>
            <atom:updated>2025-06-22T10:00:53.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced C++ (Part 1) — Demystifying shared_ptr, unique_ptr, and weak_ptr in C++</h3><h3>What are smart pointers and why use them?</h3><p>We all know that the raw pointers need to free the memory allocation in the program all the times, there are problems related to memory leakage too. Keeping this in mind C++ 11 has introduced smart pointers. There are three types of pointers as <strong>std::unique_ptr</strong>, <strong>std::shared_ptr</strong>, and <strong>std::weak_ptr, .</strong></p><h3>Unique Pointer</h3><p>It stores one pointer only at a time. We cannot copy unique_ptr, only transfer ownership of the object to another unique_ptr using the <strong>move()</strong> method.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br>    std::unique_ptr&lt;int&gt; ptr1 = std::make_unique&lt;int&gt;(10);<br>    std::cout &lt;&lt; *ptr1 &lt;&lt; std::endl;         // Outputs: 10<br>    <br>    // moving ownership of unique pointer<br>    std::unique_ptr&lt;int&gt; pt2= std::move(ptr1); //ptr1 becomes null <br>    // std::cout &lt;&lt; *ptr1 &lt;&lt; std::endl;         // Outputs: error<br>    std::cout &lt;&lt; *ptr2 &lt;&lt; std::endl;         // Outputs: 10<br>    <br>    // resetting unique pointer<br>    ptr2.reset(new int(99));<br>    std::cout &lt;&lt; *ptr2 &lt;&lt; std::endl;         // Outputs: 99<br><br>    // coyping unique pointer<br>    // std::unique_ptr&lt;int&gt; ptr2= ptr1;      // error<br>    // No need to delete - automatic cleanup or can delete pointer via ptr.reset()/ptr.release() method.<br><br>    std::cout&lt;&lt; sizeof(std::unique_ptr&lt;int&gt;)&lt;&lt; &quot; bytes\n&quot;; // outputs: 8 bytes on 64 bit compiler<br><br>}</pre><p>In the above program we see that 10 is allocated on heap and the “ptr1” which is unique is on stack having 8 bytes. We can can move the ownership of “ptr1” to “ptr2” via move() or reset to a new object to via reset(). Here we cant have a two unique pointer pointing to the same location. The smart pointer are been deallocated automatically so no need to call explicitly.</p><h3>Shared Pointer</h3><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br>    std::shared_ptr&lt;int&gt; ptr1 = std::make_shared&lt;int&gt;(10);<br>    std::cout &lt;&lt; *ptr1 &lt;&lt; std::endl;         // Outputs: 10<br><br>    // copying shared pointer<br>    std::shared_ptr&lt;int&gt; ptr2 = ptr1;        // shared ownership<br>    std::cout &lt;&lt; *ptr1 &lt;&lt; std::endl;         // Outputs: 10<br>    std::cout &lt;&lt; *ptr2 &lt;&lt; std::endl;         // Outputs: 10<br>    std::cout &lt;&lt; &quot;Use count after copy: &quot; &lt;&lt; ptr1.use_count() &lt;&lt; std::endl;  // Outputs: 2<br><br>    //reseting shared pointer<br>    ptr2.reset(new int(99));                 // ptr2 now points to new object, use_count of ptr1 drops by 1<br>    std::cout &lt;&lt; *ptr2 &lt;&lt; std::endl;         // Outputs: 99<br>    std::cout &lt;&lt; &quot;Use count after reset: &quot; &lt;&lt; ptr1.use_count() &lt;&lt; std::endl;  // Outputs: 1<br>    <br>    // moving ownership of shared pointer<br>    ptr2= std::move(ptr1);  // ptr1 is now empty (nullptr) and ptr2 points to 10 <br>    // std::cout &lt;&lt; &quot;Use count after reset: &quot; &lt;&lt; ptr1.use_count() &lt;&lt; std::endl;  // Outputs: undefined behavior may crash<br>    std::cout &lt;&lt; &quot;Use count after reset: &quot; &lt;&lt; ptr2.use_count() &lt;&lt; std::endl;  // Outputs: 1<br><br><br>    std::cout &lt;&lt; sizeof(std::shared_ptr&lt;int&gt;) &lt;&lt; &quot; bytes\n&quot;;  // Typically: 16 bytes on 64-bit<br>}</pre><p>Here we can see that an object on heap can be pointed by “ptr1” as well as “ptr2”. We can reset this pointer via reset() method and move the ownership via move() method. Here “ptr1.use_count()” tells us how many pointers are pointing to that location to which the pointer “ptr1”is pointing. The Diagram for above code as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*AyJf-a3mLvkBIfX5-6goBQ.png" /></figure><h3>Memory difference between Unique and Shared Pointer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*i-RHDrNfJFEUpIWZT4Te9w.png" /></figure><p>Unique pointer on stack only requires 8 bytes to store the address of an any object that is on the heap whereas the shared pointer on stack has to store the address of object on heap and the address of Control block associated with every shared pointer on heap. The control block stores the <strong>reference_count of shared pointer</strong> <em>(how many shared pointers are pointing to that object)</em> , <strong>reference_count of weak pointer </strong><em>(how many weak pointers are pointing to that object)</em><strong> </strong>and the custom allocator and deleter with respect to object pointed via shared pointer.</p><h3>Weak Pointer</h3><p>This is a smart pointer that holds a non-owning reference to an object. It’s much more similar to shared_ptr except it will not maintain a r<strong>eference counter</strong>. In this case, a pointer will not have a stronghold on the object. The reason is to avoid the circular dependency created by two or more object pointing to each other using shared pointer.</p><p>Below code explain us about the copying, moving and resetting of weak pointer. Here the lock() method on weak pointers gets the shared pointer address pointed by weak pointer if exist as we know weak pointer is non owning reference so weak pointer cannot be directed dereferenced so we you lock() method to get shared pointer associated with it and then dereferencing shared pointer to get the value. The .lock() method safely checks that and returns a temporary shared_ptr if the object still exists.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>int main() {<br>    std::shared_ptr&lt;int&gt; shared1 = std::make_shared&lt;int&gt;(100);<br>    std::cout &lt;&lt; *shared1; // Output: shared1 points to: 100<br><br>    // Create weak_ptr from shared_ptr<br>    std::weak_ptr&lt;int&gt; weak1 = shared1;<br>    std::cout &lt;&lt; &quot;Use count after weak1: &quot; &lt;&lt; shared1.use_count(); // Output: 1 (weak_ptr does not increase use_count)<br><br>    // Copying weak_ptr<br>    std::weak_ptr&lt;int&gt; weak2 = weak1;<br>    std::cout &lt;&lt; &quot;Use count after weak1: &quot; &lt;&lt; shared1.use_count(); // Output: 1 (weak_ptr does not increase use_count)<br><br>    // moving weak_ptr <br>    std::weak_ptr&lt;int&gt; weak3 = std::move(weak2);  // weak2 becomes empty<br><br>    // Check lock on weak1<br>    if (auto temp = weak1.lock()) {<br>        std::cout &lt;&lt; &quot;weak1 is valid, value = &quot; &lt;&lt; *temp &lt;&lt; &quot;\n&quot;;<br>        // Output: weak1 is valid, value = 100<br>    } else {<br>        std::cout &lt;&lt; &quot;weak1 has expired\n&quot;;<br>    }<br><br>    // Reset weak_ptr<br>    weak1.reset();<br><br>    // Check lock on weak1 after reset<br>    if (auto temp = weak1.lock()) {<br>        std::cout &lt;&lt; &quot;weak1 is still valid, value = &quot; &lt;&lt; *temp &lt;&lt; &quot;\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;weak1 has expired or been reset\n&quot;;<br>        // Output: weak1 has expired or been reset<br>    }<br><br>    // Now reset shared1 to destroy the resource<br>    shared1.reset();<br><br>    // Try locking weak3 (should be expired now)<br>    if (auto temp = weak3.lock()) {<br>        std::cout &lt;&lt; &quot;weak3 is still valid, value = &quot; &lt;&lt; *temp &lt;&lt; &quot;\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;weak3 has expired since shared_ptr was reset\n&quot;;<br>        // Output: weak3 has expired since shared_ptr was reset<br>    }<br><br>    std::cout &lt;&lt; sizeof(std::weak_ptr&lt;int&gt;) &lt;&lt; &quot; bytes\n&quot;; // output: 8 bytes<br>}</pre><p>At last discussing about the pros of smart pointers-</p><ul><li>Smart pointers, in simple words, are classes that wrap a pointer, or scoped pointers and it destroys itself when it goes out of its scope so No need to call delete().</li><li>Smart pointers are more efficient as they have an additional feature of memory management, clearing ownership semantics and exception safe code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b79a1ac266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Function Arguments in C++: A Complete Guide]]></title>
            <link>https://medium.com/@pratikkatkar13/mastering-function-arguments-in-c-a-complete-guide-6d5b8b06c6f9?source=rss-12008e6cb832------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d5b8b06c6f9</guid>
            <category><![CDATA[pass-by-value]]></category>
            <category><![CDATA[function-parameter]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[function-argument]]></category>
            <dc:creator><![CDATA[Pratik Bhaskar Katkar]]></dc:creator>
            <pubDate>Sat, 03 May 2025 11:49:51 GMT</pubDate>
            <atom:updated>2025-05-03T11:49:51.473Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>About Functions:</strong></h3><p>We all know a reusable part of code encoded in specific block by giving a unique name is called function. Now the parameters we pass in the code are having two different names in two different context as follows:</p><p><strong>1. Actual Parameters:</strong><br>These are the real values or variables you pass to a function when calling it. They exist in the <strong>calling function or context</strong>.</p><p><strong>2. Formal Parameters:</strong><br>These are the variables defined in the function’s definition that receive the values of actual parameters. They exist <strong>inside the function definition</strong> and act as placeholders.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void greet(string name) {       // &#39;name&#39; is a formal parameter<br>    cout &lt;&lt; &quot;Hello, &quot; &lt;&lt; name &lt;&lt; &quot;!&quot; &lt;&lt; endl;<br>}<br><br>int main() {<br>    string user = &quot;Alice&quot;;<br>    greet(user);               // &#39;user&#39; is an actual paramete<br>    return 0;<br>}<br><br>//output  - Hello Alice!</pre><h3><strong>1. Pass By value :</strong></h3><p>A <strong>copy</strong> of the actual parameter is passed to the function. Changes made <strong>do not affect</strong> the original variable.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void modify(int a) {<br>    a = a + 10;<br>    cout &lt;&lt; &quot;Inside function: &quot; &lt;&lt; a &lt;&lt; endl;<br>}<br><br>int main() {<br>    int a = 5;<br>    cout &lt;&lt; &quot;Before function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    modify(a);<br>    cout &lt;&lt; &quot;After function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    return 0;<br>}<br><br>// output -  Before function calling : 5<br>//           Inside Fuction: 15<br>//           After Function calling: 5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*F0b10Ou59DRv4mD-n2J4qw.png" /><figcaption>Description of above code.</figcaption></figure><p>Here we can see every time when we pass the value i.e. actual parameter then new variables are created with respect to the function and both function specific and main function specific variables are independent here therefore no change is seen. <strong>Space required is 4 bytes for ‘a’ of main() and 4 bytes for ‘a’ of modify() that is total space is 8 bytes (64 bit system).</strong></p><ul><li>Unnecessary memory is wasted. Copies of variables are created, which is inefficient for large structures like arrays or objects.</li><li>Copying data, especially complex objects, can slow down performance.</li></ul><h3>2. Pass by pointers / Pass by address:</h3><p>A <strong>memory address (pointer)</strong> is passed. You must use * to access or modify the original value. Changes <strong>affect the original</strong>.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void modify(int *x) {<br>    *x = *x + 10;<br>    cout &lt;&lt; &quot;Inside function: &quot; &lt;&lt; *x &lt;&lt; endl;<br>}<br><br>int main() {<br>    int a = 5;<br>    cout &lt;&lt; &quot;Before function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    modify(&amp;a);<br>    cout &lt;&lt; &quot;After function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    return 0;<br>}<br><br>// output -  Before function calling : 5<br>//           Inside Fuction: 15<br>//           After Function calling: 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*EPSCK4gUbb1jRJvugWk8uw.png" /><figcaption>Description of above code.</figcaption></figure><p>Here we pass address as actual parameter to function which in turn has a pointer which points to that address so changes are also reflected in the main(). <strong>Space required is 4 bytes for ‘a’ of main() and 8 bytes for pointer ‘x’ of modify() that is total space is 12 bytes (64 bit system).</strong></p><ul><li>You need to use * and &amp; correctly, which can confuse beginners.</li><li>Pointer-based code tends to be more error-prone and less readable. You can accidentally pass a null or uninitialized pointer, leading to runtime errors.</li></ul><h3>3. Pass by reference:</h3><p>The <strong>original variable is passed</strong>, not a copy. Changes made <strong>affect the original</strong>.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void modify(int &amp;x) {<br>    x = x + 10;<br>    cout &lt;&lt; &quot;Inside function: &quot; &lt;&lt; x &lt;&lt; endl;<br>}<br><br>int main() {<br>    int a = 5;<br>    cout &lt;&lt; &quot;Before function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    modify(a);<br>    cout &lt;&lt; &quot;After function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    return 0;<br>}<br><br>// output -  Before function calling : 5<br>//           Inside Fuction: 15<br>//           After Function calling: 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*VwPat_dnfJbR3yehjdfjew.png" /><figcaption>Description of above code.</figcaption></figure><p>Here both the ‘a’ and ‘x’ are having memory location as 814 in memory means two names for one memory space hence changes made in modify() are also seen in the main(). <strong>Space required is 4 bytes for ‘a’ of main() and 8 bytes for ‘x’ of modify() (internally implemented like a pointer, though syntactically different) that is total space 12 bytes only (64 bit system).</strong></p><ul><li>Original data can be changed unintentionally, leading to bugs.</li><li>It’s not always obvious from the call that the original data will be affected (unlike pointers which use &amp;).</li><li>You can’t pass constants or temporary expressions directly (e.g., modify(5) is invalid if function takes int &amp;).</li></ul><h3><strong>4. Pass by Constant Reference:</strong></h3><p>Passes a reference <strong>read-only</strong>; used for <strong>large objects</strong> to avoid copies without risking modification (const T&amp;).</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void modify(const int&amp; x) {<br>    // x += 5; //Error: cannot modify a const reference<br>    cout &lt;&lt; &quot;Inside function: &quot; &lt;&lt; x &lt;&lt; endl;<br>}<br><br>int main() {<br>    int a = 10;<br>    cout &lt;&lt; &quot;Before function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    modify(a);<br>    cout &lt;&lt; &quot;After function calling : &quot; &lt;&lt; a &lt;&lt; endl;<br>    return 0;<br>}<br><br>// output -  Before function calling : 5<br>//           Inside Fuction: 5<br>//           After Function calling: 5</pre><h3>5. Pass by move:</h3><p>Transfers ownership of resources from one object to another, avoiding deep copy.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;utility&gt;  // for std::move<br><br>void takeData(std::string&amp;&amp; data) {<br>    std::cout &lt;&lt; &quot;Inside function: &quot; &lt;&lt; data &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    std::string name = &quot;Bob&quot;;<br>    cout&lt;&lt;&quot;Before function calling: &quot;&lt;&lt; name &lt;&lt; std::endl;<br>    takeData(std::move(name));  // Move name into the function<br>    std::cout &lt;&lt; &quot;After move or function calling: &quot; &lt;&lt; name &lt;&lt; std::endl;<br>    return 0;<br>}<br><br>// output -  Before function calling : Bob<br>//           Inside Fuction: Bob<br>//           After move or function calling:  <br></pre><p>Here actually std::move(name) casts name into an <strong>rvalue reference</strong>. takeData(std::string&amp;&amp; data) receives ownership of the internal data buffer. After the move, name is still a valid string object, but its content is typically <strong>emptied</strong> or in an <strong>unspecified but valid</strong> state.</p><h3>6. Pass by Rvalue Reference :</h3><p>C++11 feature used to overload functions for <strong>temporary objects</strong> (rvalues). Enables move semantics (T&amp;&amp;).</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void doubleValue(int&amp;&amp; x) {<br>    x *= 2;<br>    cout &lt;&lt; &quot;Doubled rvalue: &quot; &lt;&lt; x &lt;&lt; endl;<br>}<br><br>int main() {<br>    doubleValue(15); // Works only with temporary/rvalue<br>    return 0;<br>}<br><br>//output - Doubled rvalue: 30</pre><p>Can’t pass variables (lvalues) without std::move().</p><h3>7. Pass by Value-Result / copy-in copy-out/ Pass by Copy-Restore:</h3><p>A copy is passed <strong>in</strong>, and the modified value is <strong>copied back</strong> out when the function ends. <em>It behaves like a combination of </em><strong><em>pass-by-value</em></strong><em> (on input) and </em><strong><em>pass-by-reference</em></strong><em> (on output).</em></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>void modify(int&amp; temp) {<br>    temp += 10;  // Modify the copy<br>}<br><br>int main() {<br>    int a = 5;<br>    int copy_in = a;    // Copy IN<br>    modify(copy_in);    // Modification happens<br>    a = copy_in;        // Copy OUT<br>    cout &lt;&lt; &quot;a = &quot; &lt;&lt; a &lt;&lt; endl;<br>    return 0;<br>}<br><br>// output - a=15</pre><p>A <strong>copy</strong> of the actual parameter is passed <strong>into</strong> the function. The function operates on the <strong>copy</strong>. When the function returns, the <strong>modified copy is written back</strong> to the original variable.</p><h3>Pass by pointer Vs pass by reference:</h3><p>Both methods pass an address to the function, which typically takes up the size of a pointer (e.g. 8 bytes on a 64-bit system). The key difference lies in how these addresses are used within the function.</p><p><strong>Pass by Pointer : </strong>A copy of the pointer is passed to the function. The function can then dereference this pointer to access the original variable. The pointer itself occupies memory.</p><p><strong>Pass by Reference : </strong>An alias to the original variable is passed to the function. The reference itself does not occupy separate memory on the stack. It directly refers to the original variable’s memory location.</p><p>Although the mechanisms differ slightly, the space required for storing the address (whether as a pointer or implicitly as a reference) is the same. The size is determined by the architecture’s pointer size, not the size of the data being pointed to or referenced.</p><h3>Always remember….</h3><p>In general, when you pass an array to a function in C++, it is <strong>passed as a pointer</strong>, not by value or true reference.</p><pre>void func(int arr[]) { // same as: void func(int *arr)<br>    // some code to be written....<br>}<br>int main(){<br>int myArr[5] = {1, 2, 3, 4, 5};<br>func(myArr);<br>// after fuction changes are always seen in the myArr<br>return 0;<br>}<br><br></pre><p>We cannot make it pass by value realistically as when array size is very big and copying it may led to memory insufficiency. We can pass it by reference as void func(int (&amp;arr)[]) but not suggested as it is rarely used.</p><p><em>C++ supports multiple ways of passing data to functions , each with trade-offs in safety, performance, and flexibility. From simple value and reference passing to advanced move semantics and rvalue references, choosing the right method can greatly affect your code’s efficiency and clarity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d5b8b06c6f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>