{"id":237,"date":"2020-09-01T18:56:47","date_gmt":"2020-09-01T18:56:47","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/cplusplus\/?p=237"},"modified":"2020-09-01T18:56:47","modified_gmt":"2020-09-01T18:56:47","slug":"c-oop-virtual-functions","status":"publish","type":"post","link":"https:\/\/www.kindsonthegenius.com\/cplusplus\/c-oop-virtual-functions\/","title":{"rendered":"C++ OOP &#8211; Virtual Functions"},"content":{"rendered":"<p>In this lesson, we would cover Virtual Functions. We&#8217;ll also see example where it is used.<\/p>\n<ol>\n<li><a href=\"#t1\">Introduction to Virtual Functions<\/a><\/li>\n<li><a href=\"#t2\">Using Virtual Functions<\/a><\/li>\n<li><a href=\"#t3\">Benefits of Virtual Functions<\/a><\/li>\n<li><a href=\"#t4\">Pure Virtual Function<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t1\">1. Introduction to Virtual Functions<\/strong><\/h4>\n<p>A <em><strong>virtual function<\/strong><\/em> is a member function in the base class define with the virtual keyword. It is expected to be overridden in derived classes. In order words, a virtual function is a function that should be overriden.<\/p>\n<p>A use case for virtual functions is where a pointer of the base class is pointing to an object of the derived class.<\/p>\n<p>Take for example,<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #557799;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">using<\/span> <span style=\"color: #008800; font-weight: bold;\">namespace<\/span> std;\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Parent<\/span> {\r\n   <span style=\"color: #997700; font-weight: bold;\">public:<\/span>\r\n    <span style=\"color: #333399; font-weight: bold;\">void<\/span> show() {\r\n        cout<span style=\"color: #333333;\">&lt;&lt;<\/span><span style=\"background-color: #fff0f0;\">\"I am parent!\"<\/span>;\r\n    }\r\n};\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Child<\/span> <span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">public<\/span> Parent {\r\n   <span style=\"color: #997700; font-weight: bold;\">public:<\/span>\r\n    <span style=\"color: #333399; font-weight: bold;\">void<\/span> show() {\r\n        cout<span style=\"color: #333333;\">&lt;&lt;<\/span><span style=\"background-color: #fff0f0;\">\"I am child!\"<\/span>;\r\n    }\r\n};\r\n\r\n\r\n<span style=\"color: #333399; font-weight: bold;\">int<\/span> <span style=\"color: #0066bb; font-weight: bold;\">main<\/span>() {\r\n\r\n\tParent<span style=\"color: #333333;\">*<\/span> parent;\r\n\tChild child;\r\n\r\n\tparent <span style=\"color: #333333;\">=<\/span> <span style=\"color: #333333;\">&amp;<\/span>child;\r\n\r\n\tparent<span style=\"color: #333333;\">-&gt;<\/span>show();\r\n\r\n   <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>;\r\n}\r\n<\/pre>\n<p>In this example, we have a pointer of Parent type but it holds the address of child. So we expect that the child method will be called. But no, it calls the parent method. In order words, the parent function is not overridden. Here&#8217;s to output;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">I am parent!\r\n<\/pre>\n<p>The reason, for this is that the call to the show() function is set once by the compiler as the version defined in the Parent class. This is known as <em><strong>static resolution<\/strong><\/em>, <strong><em>static linkage<\/em><\/strong> or <em><strong>early binding<\/strong><\/em>.<\/p>\n<p>Note the arrow operator(-&gt;) is used to access member functions through a pointer.<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t2\">2. Using Virtual Function<\/strong><\/h4>\n<p>In order to fix the problem describe, we can declare the show() function of the Parent as virtual. Simply add the virtual keyword. Like so:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Parent<\/span> {\r\n   <span style=\"color: #997700; font-weight: bold;\">public:<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">virtual<\/span> <span style=\"color: #333399; font-weight: bold;\">void<\/span> show() {\r\n        cout<span style=\"color: #333333;\">&lt;&lt;<\/span><span style=\"background-color: #fff0f0;\">\"I am parent!\"<\/span>;\r\n    }\r\n};\r\n<\/pre>\n<p>In this case, this function will always be overridden. This is even though the pointer is a pointer of type Parent. But it holds the address of the Child.<\/p>\n<p>The virtual keyword tells the compiler that we don&#8217;t want early binding for the given function. We&#8217;ll use <strong><em>late binding<\/em><\/strong> or <strong><em>dynamic linkage<\/em><\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t3\">3. Benefit of Virtual Function<\/strong><\/h4>\n<p>Let&#8217;s now look at an example to illustrates the benefit of virtual function. In this example<\/p>\n<p>We have a base class, Vehicle and two derived classes: Bus and Car.<\/p>\n<p>Each of these classes has a data member named &#8216;make&#8217;. Assuming this data member is initialized through their constructors. Then we have:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Vehicle<\/span> {\r\n\t<span style=\"color: #997700; font-weight: bold;\">private:<\/span> string make;\r\n\t\r\n\t<span style=\"color: #997700; font-weight: bold;\">public:<\/span> Vehicle()<span style=\"color: #333333;\">:<\/span> make(<span style=\"background-color: #fff0f0;\">\"Vehicle\"<\/span>) {} <span style=\"color: #888888;\">\/\/initialize make<\/span>\r\n   \r\n   <span style=\"color: #997700; font-weight: bold;\">public:<\/span>string getMake(){\r\n\t   <span style=\"color: #008800; font-weight: bold;\">return<\/span> make;\r\n   }\r\n};\r\n\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Car<\/span> <span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">public<\/span> Vehicle {\r\n\t<span style=\"color: #997700; font-weight: bold;\">private:<\/span> string make;\t\r\n\t\r\n\t<span style=\"color: #008800; font-weight: bold;\">public<\/span><span style=\"color: #333333;\">:<\/span> Car()<span style=\"color: #333333;\">:<\/span>make(<span style=\"background-color: #fff0f0;\">\"Car\"<\/span>) {} <span style=\"color: #888888;\">\/\/initialize make<\/span>\r\n\t\r\n\t<span style=\"color: #997700; font-weight: bold;\">public:<\/span>\tstring getMake() {\r\n\t\t<span style=\"color: #008800; font-weight: bold;\">return<\/span> make;\r\n\t}\r\n};\r\n\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Bus<\/span><span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">public<\/span> Vehicle {\r\n\t<span style=\"color: #997700; font-weight: bold;\">private:<\/span> string make;\r\n\t\r\n\t<span style=\"color: #997700; font-weight: bold;\">public:<\/span> Bus()<span style=\"color: #333333;\">:<\/span>make(<span style=\"background-color: #fff0f0;\">\"Bus\"<\/span>) {} <span style=\"color: #888888;\">\/\/initialize make<\/span>\r\n\t\r\n\t<span style=\"color: #997700; font-weight: bold;\">public:<\/span> string getMake(){\r\n\t\t<span style=\"color: #008800; font-weight: bold;\">return<\/span> make;\r\n\t}\t\t\r\n};\r\n<\/pre>\n<p>In both Car and Bus, we override getMake() in Vehicle.Now, this is fine. But we also want another method, display(). This method would display the make to the output.<\/p>\n<p>We could create this method separately for each class. But we can do better. We would make the getMake() function virtual in the Vehicle class. Next, we create a single <em><strong>display()<\/strong> <\/em>function outside all the classes. This function will accept a pointer to Vehicle type as it&#8217;s argument.<\/p>\n<p>So when this function executes, it calls the getMake() function which is virtual. Therefore the getMake in the particular derived class is called.<\/p>\n<p>The display() method and the main method is shown below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #333399; font-weight: bold;\">void<\/span> <span style=\"color: #0066bb; font-weight: bold;\">display<\/span>(Vehicle<span style=\"color: #333333;\">*<\/span> v){\r\n\tcout <span style=\"color: #333333;\">&lt;&lt;<\/span> <span style=\"background-color: #fff0f0;\">\"Vehicle: \"<\/span> <span style=\"color: #333333;\">&lt;&lt;<\/span> v<span style=\"color: #333333;\">-&gt;<\/span>getMake()<span style=\"color: #333333;\">&lt;&lt;<\/span>endl;\r\n}\r\n\r\n\r\n<span style=\"color: #333399; font-weight: bold;\">int<\/span> <span style=\"color: #0066bb; font-weight: bold;\">main<\/span>() {\r\n\r\n\tVehicle<span style=\"color: #333333;\">*<\/span> vehicle1 <span style=\"color: #333333;\">=<\/span> <span style=\"color: #008800; font-weight: bold;\">new<\/span> Vehicle();\r\n\tVehicle<span style=\"color: #333333;\">*<\/span> car1 <span style=\"color: #333333;\">=<\/span> <span style=\"color: #008800; font-weight: bold;\">new<\/span> Car();\r\n\tVehicle<span style=\"color: #333333;\">*<\/span> bus1 <span style=\"color: #333333;\">=<\/span> <span style=\"color: #008800; font-weight: bold;\">new<\/span> Bus();\r\n\r\n\tdisplay(vehicle1);\r\n\tdisplay(car1);\r\n\tdisplay(bus1);\r\n\r\n   <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>;\r\n}\r\n<\/pre>\n<p>So we have considerable reduced he amount of code required. The output is shown below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">Vehicle: Vehicle\r\nVehicle: Car\r\nVehicle: Bus\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t4\">4. Pure Virtual Functions<\/strong><\/h4>\n<p>A pure virtual function is a function declared in the base class without any definition. In other words, the function has no body.<\/p>\n<p>For example<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Parent<\/span> {\r\n\t\r\n   <span style=\"color: #997700; font-weight: bold;\">public:<\/span>\r\n\t<span style=\"color: #888888;\">\/\/Pure virtual function<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">virtual<\/span> <span style=\"color: #333399; font-weight: bold;\">void<\/span> show();\r\n};\r\n<\/pre>\n<p>In this code, the only function that could possibly be executed is the on in a derived class.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this lesson, we would cover Virtual Functions. We&#8217;ll also see example where it is used. Introduction to Virtual Functions Using Virtual Functions Benefits of &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,35],"tags":[42],"class_list":["post-237","post","type-post","status-publish","format-standard","hentry","category-c-tutorials","category-oop","tag-virtual-functions"],"_links":{"self":[{"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/posts\/237","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/comments?post=237"}],"version-history":[{"count":2,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/posts\/237\/revisions"}],"predecessor-version":[{"id":239,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/posts\/237\/revisions\/239"}],"wp:attachment":[{"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/media?parent=237"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/categories?post=237"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/cplusplus\/wp-json\/wp\/v2\/tags?post=237"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}