polymorphism-in-c++

“`html

What does polymorphism signify in C++? Have you ever pondered how the same function or operator can execute various tasks in C++? For instance, how the + symbol can be utilized for both addition and string concatenation? What mechanisms govern overloading and overriding? Such capabilities are enabled by a formidable principle in C++ known as polymorphism. So, what precisely is polymorphism? Why do we implement it? How does it contribute to creating cleaner, reusable, and more manageable code?

In this article, we will explore polymorphism in C++ thoroughly.

Table of Contents:

What is Polymorphism in C++?

Polymorphism in C++ denotes ‘many forms’, signifying the use of the same function or operator name for executing different operations based on context. For instance, envision an addition operator that behaves distinctively for an integer as opposed to a string in C++.

Polymorphism in C++:

  • Reuses code rather than rewriting it multiple times.
  • Creates cleaner code that is straightforward to comprehend.
  • Facilitates easy modifications in extensive programs.
  • Utilizes one function name for various applications.

For instance, in a smartphone, the camera button captures a photo, and by pressing it longer, it commences video recording. The same button yields different outcomes.

Types of Polymorphism in C++

There are primarily two categories of polymorphism in C++. These include:

1. Compile-time Polymorphism

Compile-time polymorphism in C++ refers to the capability of a function or operator being executed during compilation, i.e., prior to the program’s execution. It is also termed static polymorphism or early binding due to the fact that the behavior of the function or operator is determined by the compiler at compile time.

Compile-time polymorphism proves particularly advantageous as:

  • You can apply the same function name for varying tasks.
  • It enhances the readability and cleanliness of your code.
  • It prevents the necessity of writing duplicate functions with distinct names.

You can realize compile-time polymorphism in C++ primarily in two ways. These comprise:

A. Function Overloading

Function Overloading is a principle in object-oriented programming that allows the creation of multiple functions bearing the same name, functioning differently with diverse parameters. In this scenario, the compiler decides which function to invoke based on the arguments provided.

Rules for Function Overloading:

  • The function must possess the same name.
  • They should differ in type or quantity of arguments.
  • The return type of the function can differ, but simply altering the return type is insufficient for distinguishing it from another function. You must also modify the number or type of parameters to achieve overloading.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth
“““html
“”);

editor46184.setValue(decodedContent); // Establish the default text
editor46184.clearSelection();

editor46184.setOptions({
maxLines: Infinity
});

function decodeHTML46184(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}

// Function to copy code to the clipboard
function copyCodeToClipboard46184() {
const code = editor46184.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code successfully copied to clipboard!”);
jQuery(“.maineditor46184 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor46184 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Issue copying code: “, err);
});
}

function runCode46184() {
var code = editor46184.getSession().getValue();

jQuery(“#runBtn46184 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];

jQuery(“.output46184”).html(“

"+data+"");
        jQuery(".maineditor46184 .code-editor-output").show();
        jQuery("#runBtn46184 i.run-code").hide();
    }
})
}

function closeoutput46184() {	
var code = editor46184.getSession().getValue();
jQuery(".maineditor46184 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn46184").addEventListener("click", copyCodeToClipboard46184);
document.getElementById("runBtn46184").addEventListener("click", runCode46184);
document.getElementById("closeoutputBtn46184").addEventListener("click", closeoutput46184);


Output:

 Function Overloading

Explanation: In the preceding C++ code, there exist three functions named print, each with distinct parameters: int, double, and string.

B. Operator Overloading

Operator Overloading in C++ conveys a special significance to various operators such as +, -, *, etc., enabling them to function with user-defined objects. By default, operators within C++ operate only on built-in types like int and float. However, through operator overloading, we can extend their functionality to our custom types.

Operator Overloading in C++

  • Makes your code simpler to read and comprehend.
  • Facilitates writing code using operators rather than functions, such as obj1 + obj2, making the code more intuitive and legible.

Example:

Cpp
Code Copied!

Result:

Operator Overloading

Clarification: In the preceding C++ code, the addition operator is employed to sum two numbers, a and b, as well as two strings, firstName and lastName. The addition operator acts differently for integers versus strings, illustrating polymorphism in C++.

2. Runtime Polymorphism or Dynamic Polymorphism

Runtime polymorphism is a fundamental principle of object-oriented programming. It permits functions with identical names to exhibit different behaviors depending on the object's type at runtime. This concept is also referred to as late binding and dynamic polymorphism.

The compiler determines which function to invoke during the program's execution at runtime, rather than during the compilation phase.

To accomplish runtime polymorphism in C++, the following elements are utilized:

  • Inheritance: A derived class takes on characteristics from a base class, inheriting all its methods and attributes.
  • Virtual Functions: In the base class, a function is declared with the virtual keyword. This indicates to the compiler not to bind the function immediately, deferring until runtime.
  • Function Overriding: The derived class reimplements the base class’s virtual function to introduce specific functionality.
  • Base Class Pointer or Reference: A pointer/reference from the base class can hold an object of the derived class, enabling dynamic decision-making.

Runtime polymorphism in C++ can primarily be achieved via two methods:

A. Virtual Function

A virtual function is one that is declared within a base class and overridden in its derived class. At runtime, the function that is executed is contingent upon the actual object type, rather than its pointer or reference, thereby allowing runtime polymorphism. It is declared using the virtual keyword in the base class.

For instance, a remote control operates a power button that turns on the television when connected to it. Similarly, it activates a fan when linked to a fan. This illustrates that the remote performs its duties without focusing on its target, whether a fan or television. This is analogous to how a base class pointer can invoke a virtual function in the corresponding derived class based on the actual object.

Syntax of the Virtual Function

class Base {
public:
    virtual void show() {
        // base class version
    }
};

Illustration:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor78707.setValue(decodedContent); // Set the default text editor78707.clearSelection();

editor78707.setOptions({ maxLines: Infinity });

function decodeHTML78707(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard78707() { const code = editor78707.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor78707 .copymessage").show(); setTimeout(function() { jQuery(".maineditor78707 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode78707() { var code = editor78707.getSession().getValue(); jQuery("#runBtn78707 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output78707").html("

"+data+"");
            jQuery(".maineditor78707 .code-editor-output").show();
            jQuery("#runBtn78707 i.run-code").hide();
        }
    });
}
``````html
.code-editor-output").show();
                                    jQuery("#runBtn78707 i.run-code").hide();

} })

}

function closeoutput78707() { var code = editor78707.getSession().getValue(); jQuery(".maineditor78707 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn78707").addEventListener("click", copyCodeToClipboard78707); document.getElementById("runBtn78707").addEventListener("click", runCode78707); document.getElementById("closeoutputBtn78707").addEventListener("click", closeoutput78707);

Result:

Virtual Function

Clarification: In this code snippet, the Animal class includes a sound() method, which is designated as virtual, allowing it to be overridden in inherited classes. The Dog class offers its unique rendition of sound(). Although we utilize an Animal* pointer, it references a Dog, leading to the invocation of the Dog’s sound().

B. Method Overriding

When a subclass contains a method that matches the name and parameters of a superclass method, providing its implementation, this is termed method overriding. The correct method is selected during execution rather than compilation, which is why it is utilized in runtime polymorphism.

Guidelines for Method Overriding:

  1. The method name in both classes must be identical.
  2. The parameters must be identical.
  3. The return type must also match.

Method overriding can be accomplished in the following manners:

i.) Method Overriding without Virtual Method in C++

If a subclass modifies a method from the superclass, it won't be executed when called via a superclass pointer unless the method is declared as virtual. Thus, without the virtual keyword, C++ considers the pointer type rather than the actual object, deciding which method to execute prior to running the program. Hence, the superclass's method is invoked even if the object belongs to the subclass.

Illustration:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor48540.setValue(decodedContent); // Set the default text editor48540.clearSelection();

editor48540.setOptions({ maxLines: Infinity });

function decodeHTML48540(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard48540() { const code = editor48540.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor48540 .copymessage").show(); setTimeout(function() { jQuery(".maineditor48540 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode48540() {

var code = editor48540.getSession().getValue();

jQuery("#runBtn48540 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output48540").html("

"+data+"");
									jQuery(".maineditor48540 .code-editor-output").show();
									jQuery("#runBtn48540 i.run-code").hide();

} })

}

function closeoutput48540() { var code = editor48540.getSession().getValue(); jQuery(".maineditor48540 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn48540").addEventListener("click", copyCodeToClipboard48540); document.getElementById("runBtn48540").addEventListener("click", runCode48540); document.getElementById("closeoutputBtn48540").addEventListener("click", closeoutput48540);

Result:

Function Overriding without Virtual Function

Clarification: In the preceding C++ code, there exists a base class Vehicle and a subclass Car, both featuring a method start(). The pointer pointing to Vehicle* refers to a Car object. However, as the start() method in the base class is not designated as virtual, C++ invokes the base class version.

ii.) Method Overriding with Virtual Method

``````html

in C++

When a base class method is designated with the virtual keyword, and the derived class implements it with the identical name and parameters, even while using a base class pointer or reference, the derived class variant is invoked at runtime.

Illustration:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor33023.setValue(decodedContent); // Establish the default text editor33023.clearSelection();

editor33023.setOptions({ maxLines: Infinity });

function decodeHTML33023(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard33023() { const code = editor33023.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor33023 .copymessage").show(); setTimeout(function() { jQuery(".maineditor33023 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode33023() { var code = editor33023.getSession().getValue();

jQuery("#runBtn33023 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output33023").html("

"+data+"");
            jQuery(".maineditor33023 .code-editor-output").show();
            jQuery("#runBtn33023 i.run-code").hide();
        }
    })
}

function closeoutput33023() { var code = editor33023.getSession().getValue(); jQuery(".maineditor33023 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn33023").addEventListener("click", copyCodeToClipboard33023); document.getElementById("runBtn33023").addEventListener("click", runCode33023); document.getElementById("closeoutputBtn33023").addEventListener("click", closeoutput33023);

Result:

Function Overriding with Virtual Function

Clarification: In this snippet, the Vehicle class contains a start() method, and is defined as virtual, enabling it to be altered in other classes. The Car class provides its customized version of start(). Although we utilize a Vehicle* pointer, it refers to a Car, therefore the Car start() is executed.

Why Implement Polymorphism in C++?

Polymorphism in C++ facilitates the same function to act differently based on the object invoking it, which aids in crafting a universal function within a base class and subsequently overriding it in various derived classes according to requirements. Furthermore, there’s no necessity to write distinct code for each type; the appropriate function is automatically called at runtime, depending on the actual object rather than the pointer type. This is referred to as runtime polymorphism and operates through virtual functions. It also enhances code flexibility, reusability, and manageability.

Polymorphism additionally assists in minimizing code duplication. Rather than employing if-else or switch statements, you can allow the object to determine its behavior, making your program simpler to maintain and expand. For instance, if you wish to incorporate a new class, there’s no need to rewrite the existing code. This is particularly beneficial in real-world applications such as billing systems, games, drawing applications, and more.

When To Apply Inheritance and Polymorphism in C++?

1. Polymorphism

One should utilize polymorphism in C++

  • When desiring to develop code that accommodates various object types.
  • When implementing a virtual function in the base class.
  • When the functionality of one class parallels that of another class.
  • When different objects exhibit common actions, such as draw() for Circle, Rectangle, and Triangle.

2. Inheritance

One should employ inheritance in C++

  • When distinct classes must share a comparable function or data.
  • When you wish to alter an existing behavior of the class without rewriting it.
  • When the objects conform to the same fundamental structure.
  • When one class is a type of another class, such as a Car being a Vehicle, and a Dog being an Animal.

Distinction Between Runtime and Compile-Time

``````html

Feature Compile-Time Runtime
When it occurs Before execution During execution
Kind of mistakes Spelling/typing mistake Errors encountered while running
Verification type Verified early Verified later
Polymorphism category Overloading Overriding
Phase Build phase Runtime phase
Illustrative error int x = “text”; int x = 5/0;

Summary

From the preceding article, we infer that polymorphism in C++ enables the same function or operator to act differently depending on the actual object during execution. It comprises two primary categories: compile-time polymorphism, such as function and operator overloading, and runtime polymorphism, like virtual functions and function overriding. This feature promotes code reuse and contributes to clearer programming. It's extensively employed in practical applications where behavior must adapt according to the object's type.

Common Questions on Polymorphism in C++

Q1. What does polymorphism mean with an example?

Polymorphism signifies that a single item can behave in various ways. For instance, the + operator can either sum numbers or concatenate strings.

Q2. Is overloading considered a type of polymorphism?

Yes, overloading is categorized as compile-time polymorphism.

Q3. What does encapsulation refer to in C++?

Encapsulation implies grouping related data and functions into a single unit known as a class.

Q4. What is the 'this' pointer in C++?

The 'this' pointer contains the address of the current object invoking the function.

Q5. What does inheritance mean in C++?

Inheritance allows one class to utilize features of another, facilitating code reuse and expansion.

The article Polymorphism in C++ was first published on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This