Explain the concept of polymorphism in C++.

Polymorphism in C++ is a core concept of Object-Oriented Programming (OOP) that allows functions or methods to operate in different ways based on the context. There are two main types of polymorphism:

  1. Compile-time Polymorphism (Static Polymorphism): This is achieved through function overloading and operator overloading. The function to be executed is determined at compile time.

    Example of function overloading:

    class Print {
    public:
        void show(int i) {
            std::cout << "Integer: " << i << std::endl;
        }
        void show(double d) {
            std::cout << "Double: " << d << std::endl;
        }
    };
  2. Runtime Polymorphism (Dynamic Polymorphism): This is achieved through inheritance and virtual functions. The function to be executed is determined at runtime based on the object type.

    Example of runtime polymorphism:

    class Base {
    public:
        virtual void show() {
            std::cout << "Base class show function called." << std::endl;
        }
    };
    
    class Derived : public Base {
    public:
        void show() override {
            std::cout << "Derived class show function called." << std::endl;
        }
    };
    
    void display(Base* b) {
        b->show(); // Calls the appropriate show() function based on the object type
    }
    
    int main() {
        Base b;
        Derived d;
        display(&b); // Calls Base's show
        display(&d); // Calls Derived's show
        return 0;
    }

In summary, polymorphism allows for flexibility and the ability to define a single interface for different data types, enhancing code reusability and maintainability.

0 Comments

no data
Be the first to share your comment!