C++ What is Polymorphism

www.igif‮oc.aedit‬m

Polymorphism is the ability of objects of different types to be treated as if they were the same type. In C++, this is achieved through the use of virtual functions and function overloading.

Virtual functions are member functions of a base class that can be overridden in a derived class. When a virtual function is called on an object of the derived class, the derived class's implementation of the virtual function is executed, even if the object is being treated as if it were of the base class. This allows for the same method to behave differently depending on the actual type of the object it's called on.

Here's an example:

class Shape {
public:
    virtual void draw() {
        // default implementation for Shape
    }
};

class Circle : public Shape {
public:
    void draw() override {
        // implementation for Circle
    }
};

class Square : public Shape {
public:
    void draw() override {
        // implementation for Square
    }
};

int main() {
    Shape* s1 = new Circle();
    Shape* s2 = new Square();
    
    s1->draw(); // calls Circle's draw()
    s2->draw(); // calls Square's draw()
}

In this example, we have a base class Shape with a virtual function draw(). We also have two derived classes, Circle and Square, that override the draw() method with their own implementations.

In the main() function, we create two objects of type Circle and Square, but we assign them to pointers of type Shape. This allows us to call the draw() method on these objects, even though they're of different types. The output of this code will be the execution of the draw() method for the appropriate derived class, based on the actual type of the object being pointed to.

Function overloading is another way to achieve polymorphism in C++. Function overloading allows multiple functions to have the same name but different parameters. The compiler determines which function to call based on the types of the arguments passed in.

Here's an example:

void print(int x) {
    std::cout << "Printing an integer: " << x << std::endl;
}

void print(double x) {
    std::cout << "Printing a double: " << x << std::endl;
}

int main() {
    print(5);      // calls the int version of print()
    print(3.14);   // calls the double version of print()
}

In this example, we have two functions named print(), but one takes an int parameter and the other takes a double parameter. When the print() function is called with an int argument, the int version of the function is executed. When it's called with a double argument, the double version of the function is executed. This allows the same function name to be used for different types of data, which makes the code more concise and easier to read.