{"id":81731,"date":"2021-07-14T09:00:58","date_gmt":"2021-07-14T03:30:58","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81731"},"modified":"2021-07-14T09:00:58","modified_gmt":"2021-07-14T03:30:58","slug":"polymorphism-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/","title":{"rendered":"Polymorphism in C++"},"content":{"rendered":"<p>This article covers polymorphism and its types in C++ with examples. Let&#8217;s start!!!<\/p>\n<h3>What is Polymorphism?<\/h3>\n<p>The literal meaning of Polymorphism is to have many forms. In programming, this means that the same entity acts in different ways depending on situations. Polymorphism is a key concept of OOPs.<\/p>\n<p>Consider yourself as a real life example of polymorphism. Depending on situations, you perform different roles like a student, a son\/daughter, a brother\/sister, etc.<\/p>\n<h3>Types of Polymorphism in C++<\/h3>\n<p>There are two types of polymorphism in C++:<\/p>\n<h4>1. Compile-time Polymorphism in C++<\/h4>\n<p>This type of polymorphism is also referred to as static binding or early binding. It takes place during compilation.<br \/>\nWe use function overloading and operator overloading to achieve compile-time polymorphism.<\/p>\n<h5>a. Function Overloading in C++<\/h5>\n<p>In C++, two or more functions can have the same name if the number and\/or type of parameters are different, this is called function overloading. Thus, overloaded functions are functions that have the same name but different parameters.<\/p>\n<p>An overloaded function is called based on the number and type of parameters passed. Thus, the compiler picks the correct function during compilation of the program.<\/p>\n<p><strong>Examples of overloaded functions<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int add(int, int);\nint add(int, int, int);\t\t\/\/number of parameters different\ndouble add(double, double);\t\t\/\/type of parameters different\n<\/pre>\n<p><strong>Example to illustrate function overloading in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint add(int a, int b) {\n    return a+b;\n}\n\nint add(int a, int b, int c) {\n    return a+b+c;\n}\n\ndouble add(double a, double b) {\n    return a+b;\n}\n\nint main() {\n  int x = 3, y = 7, z = 12;\n  double n1 = 4.56, n2 = 13.479;\n  \n  cout&lt;&lt;\"x+y = \"&lt;&lt;add(x,y)&lt;&lt;endl;\n  cout&lt;&lt;\"x+y+z = \"&lt;&lt;add(x,y,z)&lt;&lt;endl;\n  cout&lt;&lt;\"n1+n2 = \"&lt;&lt;add(n1,n2);\n  \n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">x+y = 10<br \/>\nx+y+z = 22<br \/>\nn1+n2 = 18.039<\/div>\n<h5>b. Operator Overloading in C++<\/h5>\n<p>We can also overload operators in C++. We can change the behavior of operators for user-defined types like objects and structures.<\/p>\n<p>For example, the \u2018+\u2019 operator, used for addition, can also be used to concatenate two strings of std::string class. Its behavior will depend on the operands.<\/p>\n<p><strong>Example of Operator Overloading in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/Using + operator to add complex numbers\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass complex {\n    private:\n    float real, imag;\n    public:\n    complex(float r=0, float i=0){\n        real = r;\n        imag = i;\n    }\n    complex operator + (complex const &amp;obj) {\n        complex result;\n        result.real = real + obj.real;\n        result.imag = imag + obj.imag;\n        return result;\n    }\n    void display() {\n        cout&lt;&lt;real&lt;&lt;\"+i\"&lt;&lt;imag&lt;&lt;endl;\n    }\n};\n\nint main() {\n  complex c1(12.4,6), c2(7.9,8);\n  complex c3 = c1 + c2;\n  c3.display();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">20.3+i14<\/div>\n<h4>2. Run-time Polymorphism in C++<\/h4>\n<p>Run-time polymorphism takes place when functions are invoked during run time. It is also known as dynamic binding or late binding. Function overriding is used to achieve run-time polymorphism.<\/p>\n<h5>a. Function Overriding in C++<\/h5>\n<p>When a member function of a base class is redefined in its derived class with the same parameters and return type, it is called function overriding in C++. The base class function is said to be overridden.<\/p>\n<p>The function call is resolved during run time and not by the compiler.<\/p>\n<p><strong>Example to illustrate function overriding in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass base {\n    public:\n    virtual void display() {\n        cout&lt;&lt;\"Function of base class\"&lt;&lt;endl;\n    }\n};\nclass derived : public base {\n    public:\n    void display() {\n        cout&lt;&lt;\"Function of derived class\"&lt;&lt;endl;\n    }\n};\n\nint main() {\n  derived d1;\n  d1.display();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Function of derived class<\/div>\n<h4>Virtual Function in C++<\/h4>\n<p>A virtual function is a function defined in the base class with virtual keyword. The purpose of virtual function is to ensure that the function is overridden.<\/p>\n<p>If we do not use virtual keyword with the base class function, it may not be overridden. We can still access it using a base class pointer. If the base class pointer points to the derived class object, the base class function will get executed.<\/p>\n<p>Let\u2019s see an example to understand this.<\/p>\n<p><strong>Example to illustrate the need of virtual function for function overriding in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass base {\n    public:\n    void display() {\n        cout&lt;&lt;\"Function of base class\"&lt;&lt;endl;\n    }\n};\nclass derived : public base {\n    public:\n    void display() {\n        cout&lt;&lt;\"Function of derived class\"&lt;&lt;endl;\n    }\n};\n\nint main() {\n  derived d;\n  base *b = &amp;d;   \/\/base class pointer\n  b-&gt;display();   \/\/base class function executes\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Function of base class<\/div>\n<p><strong>Example of run-time polymorphism using two derived classes<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Polygon {\n    public:\n    virtual void show() {\n        cout&lt;&lt;\"Its a polygon\"&lt;&lt;endl;\n    }\n};\nclass Triangle : public Polygon {\n    public:\n    void show() {\n        cout&lt;&lt;\"Triangle is 3 sided polygon\"&lt;&lt;endl;\n    }\n};\nclass Rectangle : public Polygon {\n    public:\n    void show() {\n        cout&lt;&lt;\"Rectangle is 4 sided polygon\"&lt;&lt;endl;\n    }\n};\n\nint main() {\n  Polygon *p;\n  Triangle t;\n  Rectangle r;\n  p = &amp;t;\n  p-&gt;show();\n  p = &amp;r;\n  p-&gt;show();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Triangle is 3 sided polygon<br \/>\nRectangle is 4 sided polygon<\/div>\n<h3>Run-time Polymorphism with Data Members<\/h3>\n<p>Run-time polymorphism can also be achieved through data members.<\/p>\n<p><strong>Example of run-time polymorphism with data members<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nclass Animal {\n    public:\n    string name = \"Animal\";\n};\nclass Dog : public Animal {\n    public:\n    string name = \"Dog\";\n};\n\nint main() {\n  Dog d;\n  cout&lt;&lt;d.name;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Dog<\/div>\n<h3>C++ Compile-time Polymorphism vs Run-time Polymorphism<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Compile-time Polymorphism<\/b><\/td>\n<td><b>Run-time Polymorphism<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Also called static or early binding.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Also called dynamic or late binding.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Achieved through overloading.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Achieved through overriding.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">The function to be executed is known during compile time.<\/span><\/td>\n<td><span style=\"font-weight: 400\">The function to be executed is known during run time.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Faster is execution.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Slow in execution.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Provides less flexibility.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Provides more flexibility.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Summary<\/h3>\n<p>In this article, we learnt about polymorphism in C++. There are two types of polymorphism in C++, compile-time and run-time polymorphism. Function overloading and operator overloading are used to achieve compile-time polymorphism.<\/p>\n<p>Function overriding is used to achieve run-time polymorphism. We learnt these with the use of suitable examples. We also understood the need of virtual functions for function overriding. Lastly, we listed the differences in the two types of polymorphism.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article covers polymorphism and its types in C++ with examples. Let&#8217;s start!!! What is Polymorphism? The literal meaning of Polymorphism is to have many forms. In programming, this means that the same entity&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81816,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3770,3771,3772,3773],"class_list":["post-81731","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-compile-time-polymorphism-in-c","tag-polymorphism-in-c","tag-run-time-polymorphism-in-c","tag-virtual-function-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Polymorphism in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about two types of polymorphism in C++, compile-time and run-time polymorphism with examples. Understand difference between them.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Polymorphism in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about two types of polymorphism in C++, compile-time and run-time polymorphism with examples. Understand difference between them.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-14T03:30:58+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Polymorphism in C++ - TechVidvan","description":"Learn about two types of polymorphism in C++, compile-time and run-time polymorphism with examples. Understand difference between them.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Polymorphism in C++ - TechVidvan","og_description":"Learn about two types of polymorphism in C++, compile-time and run-time polymorphism with examples. Understand difference between them.","og_url":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-14T03:30:58+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Polymorphism in C++","datePublished":"2021-07-14T03:30:58+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/"},"wordCount":648,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#primaryimage"},"thumbnailUrl":"","keywords":["Compile time polymorphism in C++","polymorphism in C++","run-time polymorphism in C++","virtual function in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/","name":"Polymorphism in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#primaryimage"},"thumbnailUrl":"","datePublished":"2021-07-14T03:30:58+00:00","description":"Learn about two types of polymorphism in C++, compile-time and run-time polymorphism with examples. Understand difference between them.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/polymorphism-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Polymorphism in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81731","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81731"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81731\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81731"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81731"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81731"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}