C++ being a value oriented language doesn't seem to support OO (and thus sub-typing polymorphism) very well. As for parametric polymorphism, lack of type inference on type parameters and verbose syntax of templates makes them challenging to use.
Please note that the only languages I know moderately well are Java (sub-typing polymorphism) and Haskell (parametric polymorphism). Both languages are leaned towards one kind of polymorphism. However C++ supports both (to some extent), but both seem to work in a matter that I find unintuitive. So when programming in C++ I have a pretty hard time in deciding what way I should exactly code.
So my question is what kind of polymorphism is considered more idiomatic in C++?
EDIT 1:
Explanation of my "C++ doesn't support OO well" point:
Dynamic method dispatch and LSP are very common in OO, aren't they? But when it comes to C++, applying these techniques without resorting to pointers (raw or smart) is not possible (or practical).
For example,consider a class Person
with virtual
method print
which prints his name to the console. Let there be another class Student
that extends Person
and overrides print
to print his name plus his school's name.
Now consider the following function:
void blah(const Person & p) {
p.print();
}
Here if I pass a Student
object, print
method would invoke print
from Person
, not from Student
. Thus it defies the very basic idea of subtyping polymorphism.
Now I am aware that I can use dynamic allocation (i.e. pointers) to achieve subtyping polymorphism in this case. However static allocation is more common in C++. Pointers are used as last resort (I remember having read it in some other thread here).So I find it difficult it difficult to reconcile the Good Practices that recommend static allocation over dynamic allocation (this is what I meant when I said C++ is value oriented) with subtyping polymorphism.
When using Java, I tend to use dynamic allocation all over and thus subtyping polymorphism is quite natural there. This is not the case with C++ however,
Hope my point is clear now.
EDIT 2:
Okay, the example I gave in my edit 1 is wrong. But my point is still valid and I have faced the problem many times. I am unable to recall all those cases top of my head.
Here's one case that comes to my mind.
In Java you can have reference of super type in your classes and then make them point to instances of any of its subtypes.
For example,
class A {
B y1;
B y2;
}
abstract class B {
// yada yada
}
class B1 exyends B {
// yada yada
}
class B2 extends B {
// yada yada
}
Here the references y1
and y2
in A
can be made to point to instances of either B1
, B2
or any other subclass of B
. C++ references cannot be reassigned. So I will have to use pointers here. So this provs that in C++ it's not possible to achieve all sorts of subtyping polymorphism without using pointers.