{"id":13716,"date":"2025-03-19T09:05:00","date_gmt":"2025-03-19T04:05:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=13716"},"modified":"2025-11-11T09:35:48","modified_gmt":"2025-11-11T04:35:48","slug":"virtual-and-pure-virtual-functions-in-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/03\/19\/virtual-and-pure-virtual-functions-in-c\/","title":{"rendered":"Virtual and Pure Virtual Functions in C++"},"content":{"rendered":"\n<p>In our previous lessons, we explored how inheritance allows one class to reuse and extend the features of another. We also learned about function overriding, where a derived class can redefine the behavior of a base class function.<\/p>\n\n\n\n<p>But there\u2019s a deeper question that often puzzles students:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>If a base class pointer points to a derived class object, which version of the function will be called; the one from the base or the one from the derived class?<\/em><\/p>\n<\/blockquote>\n\n\n\n<p>This question brings us to an important concept called <strong>Virtual Functions<\/strong>, one of the most powerful features of polymorphism in C++.<\/p>\n\n\n\n<p>A simple way to define it is:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A virtual function is a function in a base class that can be redefined in derived classes, and its call is resolved at runtime rather than compile time.<\/p>\n<\/blockquote>\n\n\n\n<p>In simpler terms, C++ waits until the program is running to decide which function version to call; depending on the type of object the pointer is actually pointing to.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Real-Life Example: Employees and Their Duties<\/h2>\n\n\n\n<p>Imagine a company that hires many types of employees \u2014 teachers, engineers, and managers. Each of them performs a different duty, but the company only knows that everyone must <em>perform duty<\/em>.<\/p>\n\n\n\n<p>The company management doesn\u2019t need to know the exact details of what each person does. It just asks the employee to perform the duty, and the employee responds according to their role.<\/p>\n\n\n\n<p>A teacher will teach, an engineer will design, and a manager will manage.<\/p>\n\n\n\n<p>This simple relationship reflects what <strong>virtual functions<\/strong> do in programming. The base class represents the company rule, and the derived classes represent the employees who perform different duties. When the company calls <code>performDuty()<\/code>, the correct action is performed depending on the actual employee type.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding Virtual Functions Through Code<\/h2>\n\n\n\n<p>Let\u2019s now bring this idea into C++ with an example based on our company example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\n\/\/ Base class representing a generic employee\nclass Employee {\npublic:\n    \/\/ Declaring a virtual function\n    virtual void performDuty() {\n        cout &lt;&lt; \"Performing a general company duty.\" &lt;&lt; endl;\n    }\n};\n\n\/\/ Derived class representing a Teacher\nclass Teacher : public Employee {\npublic:\n    void performDuty() override {\n        cout &lt;&lt; \"Teaching students and preparing lessons.\" &lt;&lt; endl;\n    }\n};\n\n\/\/ Derived class representing an Engineer\nclass Engineer : public Employee {\npublic:\n    void performDuty() override {\n        cout &lt;&lt; \"Designing systems and writing code.\" &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Employee* staff;  \/\/ Base class pointer\n\n    Teacher t;\n    Engineer e;\n\n    staff = &amp;t;\n    staff-&gt;performDuty();   \/\/ Calls Teacher\u2019s version\n\n    staff = &amp;e;\n    staff-&gt;performDuty();   \/\/ Calls Engineer\u2019s version\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>In this program, the base class <code>Employee<\/code> declares the function <code>performDuty()<\/code> as virtual.<br>Both <code>Teacher<\/code> and <code>Engineer<\/code> redefine this function in their own way.<\/p>\n\n\n\n<p>When we use the base class pointer <code>staff<\/code> to point to a <code>Teacher<\/code> object, it calls the teacher\u2019s version. When we point it to the engineer, it calls the engineer\u2019s version.<\/p>\n\n\n\n<p>This is called <strong>runtime polymorphism<\/strong> because the exact version of the function is decided at runtime, depending on the actual object being pointed to.<\/p>\n\n\n\n<p>If we had not used the <code>virtual<\/code> keyword, the compiler would have always called the base class version, ignoring the derived ones. That would be <strong>static binding<\/strong>. By declaring the function virtual, we enable <strong>dynamic binding<\/strong>; the true essence of polymorphism.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Moving Forward: The Need for Pure Virtual Functions<\/h2>\n\n\n\n<p>Sometimes, we don\u2019t even want the base class to provide any implementation. We just want it to declare what <em>must<\/em> be done, leaving it to the derived classes to decide <em>how<\/em> it\u2019s done.<\/p>\n\n\n\n<p>This situation is like a company rulebook that defines the responsibilities of all employees but doesn\u2019t describe how to perform them. Every employee must follow the rule and perform their specific duty.<\/p>\n\n\n\n<p>The rulebook is the <strong>abstract base class<\/strong>, and the rule itself \u2014 the declaration \u2014 is the <strong>pure virtual function<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Code Example for Pure Virtual Function<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\n\/\/ Abstract base class (acts like a rulebook)\nclass Employee {\npublic:\n    \/\/ Pure virtual function - notice the = 0\n    virtual void performDuty() = 0;\n};\n\n\/\/ Derived class: Teacher\nclass Teacher : public Employee {\npublic:\n    void performDuty() override {\n        cout &lt;&lt; \"Teaching students and preparing lessons.\" &lt;&lt; endl;\n    }\n};\n\n\/\/ Derived class: Engineer\nclass Engineer : public Employee {\npublic:\n    void performDuty() override {\n        cout &lt;&lt; \"Designing systems and writing code.\" &lt;&lt; endl;\n    }\n};\n\nint main() {\n    \/\/ We cannot create an object of Employee (abstract class)\n    \/\/ Employee e;   \/\/ \u274c This will cause a compilation error\n\n    Employee* staff;  \/\/ Base class pointer\n\n    Teacher t;\n    Engineer e1;\n\n    staff = &amp;t;\n    staff-&gt;performDuty();   \/\/ Calls Teacher\u2019s implementation\n\n    staff = &amp;e1;\n    staff-&gt;performDuty();   \/\/ Calls Engineer\u2019s implementation\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, <code>performDuty()<\/code> is declared as a <strong>pure virtual function<\/strong> using <code>= 0<\/code>.<br>This means the base class <code>Employee<\/code> defines what every employee must do but doesn\u2019t explain how to do it. Each derived class provides its own version of the function.<\/p>\n\n\n\n<p>A class that contains even one pure virtual function becomes an <strong>abstract class<\/strong>, meaning you cannot create its objects. Instead, it serves as a blueprint for other classes.<\/p>\n\n\n\n<p>If a derived class fails to implement the pure virtual function, it too becomes abstract and cannot create objects.<\/p>\n\n\n\n<p>This mechanism helps maintain consistency and ensures that all derived classes follow the same structure but with their own unique behavior.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Connecting Back to the Concept<\/h2>\n\n\n\n<p>A <strong>virtual function<\/strong> gives flexibility. It allows a base class to provide a default version that can be overridden when necessary.<\/p>\n\n\n\n<p>A <strong>pure virtual function<\/strong> enforces a rule; it doesn\u2019t define any version and leaves the implementation entirely to derived classes.<\/p>\n\n\n\n<p>Both together form the foundation of polymorphism in C++: virtual functions enable <strong>runtime decisions<\/strong>, and pure virtual functions provide <strong>structured abstraction<\/strong>.<\/p>\n\n\n\n<p>In this way, C++ beautifully balances freedom and discipline \u2014 allowing you to create systems that are flexible, scalable, and logically consistent.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task for You<\/h2>\n\n\n\n<p>Design a base class called <code>PaymentMethod<\/code> that declares a pure virtual function named <code>makePayment()<\/code>. Then, create two derived classes \u2014 <code>CashPayment<\/code> and <code>OnlinePayment<\/code>.<\/p>\n\n\n\n<p>Each class should define its own version of <code>makePayment()<\/code> describing how the payment is processed. Finally, use a base class pointer to call both versions dynamically.<\/p>\n\n\n\n<p>By completing this, you will experience how <strong>abstraction<\/strong> and <strong>runtime polymorphism<\/strong> combine to make your programs cleaner and more powerful.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our previous lessons, we explored how inheritance allows one class to reuse and extend the features of another. We also learned about function overriding, where a derived class can redefine the behavior of a base class function. But there\u2019s a deeper question that often puzzles students: If a base class pointer points to a derived class object, which version of the function will be called; the one from the base or the one from the derived class? This question&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/03\/19\/virtual-and-pure-virtual-functions-in-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":13718,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[637],"tags":[603,728,727],"class_list":["post-13716","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oop-with-c","tag-oop","tag-pure-virtual-functions","tag-virtual-function"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2025\/11\/OOP-3.jpg?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-3ze","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/13716","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=13716"}],"version-history":[{"count":1,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/13716\/revisions"}],"predecessor-version":[{"id":13719,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/13716\/revisions\/13719"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/13718"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=13716"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=13716"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=13716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}