I am reading some C++ text at the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.082/content/adhoc.html.
In the section UNIVERSAL POLYMORPHISM
, the author mentioned about Parametric
and Inclusion
polymorphisms. I am not quite sure that I understand the point, especially why Parametric
polymorphism is implemented at compile time while Inclusion
polymorphism is implemented at run time?
Can anyone give me a clear explanation or an example, please?
"Parametric polymorphism" in C++ means templates.
I think that "inclusion polymorphic" in C++ means polymorphic the way the Standard refers to it: virtual methods, subclasses and the like.
I think the names are clumsy and smack of academia.
I think by 'Parametric' it refers to method/function overloading
- we can determine what method is to be used at compile time by looking at the datatype of it's parameters.
And by 'inclusion' it means method/function overriding
- in a parent sub-class relation, if both parent and child class have the same function then it would be determined at runtime (depending on the object type) what method would be invoked.
I understood universal polymorphism to be different from what we expect in C++. C++ is ad-hoc polymorphism.
Universal says there can be only version of the same signature, regardless of the number of types.
I think the other answers skim over the detail that parametric and inclusion are categories of universal. Given the original text, I can see how they or I have been confused. ;)
Given the below:
struct Foo {
virtual void foo();
};
struct Bar {
virtual void bar();
// virtual void foo(); // this would error
};
Parametric would be like:
struct FooBar : public Foo, public Bar {};
The signatures contained in FooBar
is statically determined at compile time.
C++ does not directly support inclusion polymorphism. They would be closer to injection that you might find in scripting languages where functions are first order.
Please don't take this code literally, it is just for demonstration.
struct FooBar {};
int main() {
FooBar foob;
foob.foo = Foo::foo;
foob.bar = Bar::bar;
return 0;
}
FooBar
doesn't know its interface at compile time, it is dynamically composed. I've used similar behavior in javascript and Lua, and I'm sure many others have the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With