C++

Polymorphism in C++ Examples

Polymorphism, which implies “various forms,” happens when multiple classes are connected via heredity. Under various contexts, the very same thing (method or operator) acts differently. We may inherit properties and functions from some other class via heredity. Polymorphism uses these techniques for a variety of purposes. This enables us to carry out a particular activity in various ways. Therefore, within this article, we will discuss examples of polymorphism in C++ using some examples within Ubuntu 20.04. We have been starting it with creating and launching a new C++ file in the terminal console.

$ touch polymorphism.cc
$ nano polymorphism.cc

Example 01: Function Overloading

When their arguments are unique, you can utilize two primary functions with the same title in C++. Various methods are called based on the quantity and kind of parameters, and this concept is known as function overloading. We have started our first example with the standard “Std” namespace and “iostream” input-output header. Three user-defined same names “val” functions are defined, each containing a single cout statement. The first function contains an integer type parameter, the second contains the double type parameter, and the last contains two double-type parameters. The first two “val” functions simply get value from the main() method and display it on the shell via the cout statement. The third one is getting two double-type values from the main()and displaying the sum of both values on the shell with the help of the cout clause. The main() function is simply calling three same-name methods one after another by passing different values.

#include <iostream>
using namespace std;
int val(int n1) {
    cout <<"Integer: "<< n1 <<endl;
}
double val(double n1){
    cout <<"Double: "<< n1 <<endl;
}
double val(double n1, double n2) {
    cout << "Sum: "<< n1+n2<<endl;
}
int main() {
    val(10);
    val(9.25);
    val(4.1, 8.23);
    return 0;
}

The compilation of this C++ code is successful using the G++ compiler on the shell.

$ g++ polymorphism.cc

After executing the code, we have the values displayed on the console below.

$ ./a.out

Example 02: Operator Overloading

Operator overloading is similar to method overloading because it uses the same sign but various operands for distinct operator methods. So, we have started this example by declaring a new class “A” after the namespace and header library. Class A contains a private data member of integer type “v,” and a constructor function A() used to initialize the variable “v” with a value of 5. Here comes the operator function to increment the value of “v” by 3. As its name shows, the operator “+” has been overloaded here. The show() function is here to show the incremented value of a variable “v.” Upon creation of an object, the constructor A() will be executed. The object has been used to call the “++” operator function. The obj is again utilized to call the show() function to display the incremented value.

#include <iostream>
using namespace std;
class A {
   private:
    int v;
   public:
    A() : v(5) {}
    void operator ++() {
        v = v + 3;
    }
    void show() {
        cout << "Value after increment: " << v << endl;
    }
};
int main() {
    A obj;
    ++obj;
    obj.show();
    return 0;  
}

After the compilation, we have got no errors. The incremented value of variable “v” has been displayed on our terminal screen upon running this code.

$ g++ polymorphism.cc
$ ./a.out

Example 03: Function Overriding

The base class and its descendant subclasses can have the same name methods. When we use an instance from the subclass to invoke the method, the extended class’s function is run rather than the parent class’s. As a result, various functions will run depending on the object invoking the method. In C++, this is referred to as method overriding. So, we have initialized three classes in the code. Class A is the parent class of both child classes B and C. All classes have the same name function, “show(),” displaying its specs via cout statement. The main() method has created 3 objects for 3 classes to call the respective functions.

#include <iostream>
using namespace std;
class A {
   public:
    void show() {
        cout << "Base class A... " << endl;
    }};
class B : public A {
   public:
    void show() {
        cout << "Derived class B... " << endl;
    }};
class C : public A {
   public:
    void show() {
        cout << "Derived class C... " << endl;
    }};
int main() {
    A o1;
    o1.show();
    B o2;
    o2.show();
    C o3;
    o3.show();
    return 0;
}

We have got all the methods executed from all the classes upon running this code file.

Example 04: Virtual Functions

If we use a base class reference “pointer” to refer to a derivative class object, we may not even be capable of circumvent methods in C++. In these circumstances, the use of virtual methods in the parent class assures that the method can be overridden. So, we have created a parent class A with its child class B. Both the classes have the same name functions, but the parent class function contains the keyword “virtual.” In main(), the B class object “b” has been used as a reference to the parent class “A” pointer object “a.”

#include <ostream>
using namespace std;
class A {
   public:
    virtual void show() {
        cout << "Base class A..." << endl;
    }
};
class B : public A {
   public:
    void show() {
        cout << "Derived class B..." <show();
    return 0;
}

Upon executing this code, the derived class method has been executed using the virtual keyword in the parent class user-defined same-name function.

$ g++ polymorphism.cc
$ ./a.outg

Conclusion:

This was all about using polymorphism in C++ using some of its basic concepts. To make it smooth, we have covered function overloading, function overriding, operator overloading, and virtual function concept. We are hoping for the best feedback for this work.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.