C++ Polymorphism

Explanation of Polymorphism in C++

What is Polymorphism?

Polymorphism is a key idea in object-oriented programming that lets one object be treated as many forms. It allows objects of different classes to be handled as objects of a common base class. In C++, polymorphism is made possible by inheritance and virtual functions.

  • Inheritance: This allows a class to inherit the properties and actions of another class, called the base class. By making a derived class from a base class, objects can be treated as both the base class type and the derived class type. This means one object can be used in different ways depending on the context.
  • Virtual Functions: These are member functions declared in the base class and overridden in the derived class. When a virtual function is called using a base class pointer or reference, the correct derived class function is called based on the actual object type at runtime. This allows different derived class objects to be treated as base class objects, enabling polymorphic behavior.

Polymorphism helps in code reuse, makes the code easier to maintain, and allows for extending the code more easily. It keeps the internal details of derived classes hidden from the client code, which is good for encapsulation. Overall, polymorphism is a powerful tool that makes object-oriented programs in C++ flexible and versatile.

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

Master coding skills by choosing your ideal learning course

View all courses