Reputation: 99
Can overloading be considered as an implementation of polymorphism? If they are the same then why are two different words used?
Upvotes: 3
Views: 4113
Reputation: 145204
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.
Upvotes: 8
Reputation: 10348
Yes, overloading is a form of static polymorphism, Ad hoc polymorphism to be precise.
It is NOT dynamic polymorphism (Subtyping), which is what people usually refer to in the context of C++.
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
Upvotes: 3