Jayraj Srikriti Naidu Jayraj Srikriti Naidu - 3 months ago 19
C++ Question

C++ polymorphism and overloading?

Can overloading be considered as an implementation of polymorphism? If they are the same then why are two different words used?

Answer

Yes, overloading is a form of static polymorphism (compile time polymorphism). However, in C++ the expression “polymorphic class” refers to a class with at least one virtual member function. I.e., in C++ the term “polymorphic” is strongly associated with dynamic polymorphism.

The term override is used for providing a derived class specific implementation of a virtual function. In a sense it is a replacement. An overload, in contrast, just provides an ┬╣additional meaning for a function name.

Example of dynamic polymorphism:

struct Animal
{
    virtual auto sound() const
        -> char const* = 0;
};

struct Dog: Animal
{
    auto sound() const
        -> char const* override
    { return "Woof!"; }
};

#include <iostream>
using namespace std;

auto main()
    -> int
{
    Animal&& a = Dog();
    cout << a.sound() << endl;
}

Example of static polymorphism:

#include <iostream>
using namespace std;

template< class Derived >
struct Animal
{
    void make_sound() const
    {
        auto self = *static_cast<Derived const*>( this );
        std::cout << self.sound() << endl;
    }
};

struct Dog: Animal< Dog >
{
    auto sound() const -> char const* { return "Woof!"; }
};

auto main()
    -> int
{ Dog().make_sound(); }

Notes:
┬╣ Except when it shadows the meanings provided by a base class.