C++ Polymorphism

What is Polymorphism?

Polymorphism plays a role in object oriented programming by enabling an object to take on multiple forms. It facilitates the handling of objects from classes as if they belong to a common base class. In C++ polymorphism is achieved through inheritance and virtual functions.

  • Inheritance involves a class inheriting the attributes and behaviors of another class known as the base class. By creating a derived class from a base class objects can be treated as both types allowing for usage based on the context.
  • Virtual functions are member functions declared in the base class and overridden in the derived class. When invoking a function using a base class pointer or reference the correct function from the derived class is executed based on the actual object type during runtime. This capability enables treating derived class objects as if they were base class objects thereby enabling polymorphic behavior.

Polymorphism promotes code reusability simplifies code maintenance and facilitates code extension. It conceals details of derived classes, from client code enhancing encapsulation. In essence polymorphism serves as a tool that enhances flexibility and versatility in C++ object oriented programs.

Importance of Polymorphism in Object-Oriented Programming

Polymorphism is essential in object-oriented programming because it allows objects of different classes to be used in the same way, making the code more reusable and flexible. Polymorphism can be achieved in several ways:

  • Compile-time Polymorphism: Also known as static polymorphism, this happens when the function to be called is decided at compile time. Examples include function overloading and operator overloading.
  • Runtime Polymorphism: Also known as dynamic polymorphism, this happens when the function to be called is decided at runtime. This is achieved using virtual functions in C++.
  • Function Overloading: This allows multiple functions with the same name but different parameters. The right function is chosen based on the arguments used when calling the function.
  • Operator Overloading: This allows you to define how operators work with user-defined types. For example, you can define how the + operator works for a class representing complex numbers.
  • Dynamic Binding: This determines the correct function implementation at runtime based on the actual object type. This is crucial for runtime polymorphism.

Polymorphism allows us to write more general and reusable code, making it easier to maintain and extend.

Types of Polymorphism in C++

Introduction

Polymorphism in C++ allows objects to be represented in multiple forms. It provides flexibility and makes the code more extensible. There are two main types of polymorphism in C++: compile-time polymorphism and runtime polymorphism.

Compile-time Polymorphism

Compile-time polymorphism happens when the function to be called is decided at compile time. This includes function overloading and operator overloading.

Function Overloading

Function overloading allows multiple functions with the same name but different parameters. The compiler selects the right function based on the arguments provided.


void print(int i) {
    std::cout << "Printing int: " << i << std::endl;
}

void print(double f) {
    std::cout << "Printing float: " << f << std::endl;
}

void print(std::string s) {
    std::cout << "Printing string: " << s << std::endl;
}

Operator Overloading

Operator overloading allows defining how operators work with user-defined types.


class Complex {
public:
    int real, imag;

    Complex operator + (const Complex& obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
    }
};

Runtime Polymorphism

Runtime polymorphism happens when the function to be called is decided at runtime. This is achieved using virtual functions.

Virtual Functions

Virtual functions allow a function to be overridden in derived classes. The correct function is called based on the actual object type at runtime.


class Base {
public:
    virtual void display() {
        std::cout << "Display Base class" << std::endl;
    }
};

class Derived : public Base {
public:
    void display() {
        std::cout << "Display Derived class" << std::endl;
    }
};

int main() {
    Base* b;
    Derived d;
    b = &d;
    b->display(); // Calls Derived class display function
    return 0;
}

Virtual Functions in C++

What are Virtual Functions?

Virtual functions allow derived classes to override a function in the base class. The keyword virtual is used to declare a function as virtual in the base class.

Basics of Virtual Functions

  • Declaration: Use the virtual keyword in the base class.
  • Override: Derived classes override this function using the same function signature.
  • Dynamic Binding: The function call is resolved at runtime based on the actual object type.

Example


class Base {
public:
    virtual void show() {
        std::cout << "Base class" << std::endl;
    }
};

class Derived : public Base {
public:
    void show() {
        std::cout << "Derived class" << std::endl;
    }
};

int main() {
    Base* b;
    Derived d;
    b = &d;
    b->show(); // Calls Derived class show function
    return 0;
}

In this example, show is a virtual function. When called through a base class pointer pointing to a derived class object, it calls the derived class's show function, demonstrating runtime polymorphism.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate