Search code examples
c++programming-languagespolymorphismidioms

What kind of polymorphism is considered more idiomatic in C++?


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.


Solution

  • Having added the fifth vote to reopen gives me a chance at being the first to add another reply. Let's start with the claim that C++ doesn't support OO well. The example given is:

    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.

    To make a long story short, this example is just plain wrong -- or more accurately, the claim made about the example is wrong. If you pass a Student object to this function, what will be invoked will be Student::print, not Person::print as claimed above. Thus, C++ implements polymorphism exactly as the OP apparently wishes.

    The only part of this that isn't idiomatic C++ is that you normally use operator<< to print out objects, so instead of print (apparently) printing only to std::cout, you should probably have it take a parameter, and instead of blah, overload operator<<, something like:

    std::ostream &operator<<(std::ostream &os, Person const &p) { 
        return p.print(os);
    }
    

    Now, it is possible to create a blah that would act as described, but to do so you'd have to have it take its parameter by value:

    void blah(Person p) { 
        p.print();
    }
    

    So there is some degree of truth to the original claim -- specifically, when/if you want to use polymorphism, you do need to use pointers or references.

    Note, however, that this isn't related (any more than peripherally) to how you allocate objects. You can pass by reference regardless of how the object in question was allocated. If a function takes a pointer, you can pass the address of an automatically or statically allocated object. If it takes a reference, you can pass a dynamically allocated object.

    As far as type inference goes, C++ has it for function templates, but not class templates. C++0x adds decltype and a new meaning for auto (which has been a reserved word, but essentially never used almost since the dawn of C) that allow type inference for a wider variety of situations. It also adds lambdas (the lack of which really is a serious problem with the current C++), which can use auto. There are still situations where type inference isn't supported, but would be nice -- but at least IMO, auto (in particular) reduces that quite a bit.

    As far as verbosity goes, there's little question that it's at least partly true. Somewhat like Java, your degree of comfort in writing C++ tends to depend to at least some degree on an editor that includes various "tricks" (e.g., code completion) to help reduce the amount you type. Haskell excels in this respect -- Haskell lets you accomplish more per character typed than almost any other language around (APL being one of the few obvious exceptions). At the same time, it's worth noting that "generics" (in either Java or C#) are about as verbose, but much less versatile than C++ templates. In terms of verbosity, C++ stands somewhere between Haskell at (or close to) one extreme, and Java and C# at (or, again, close to) the opposite extreme.

    Getting to the original question of which is used more often: there was a time when C++ didn't have templates, so essentially your only choice was subtyping. As you can probably guess, at that time it was used a lot, even when it wasn't really the best choice.

    C++ has had templates for a long time now. Templates are now so common that they're essentially unavoidable. Just for example, IOStreams, which originally used only inheritance, now also use templates. The standard containers, iterators, and algorithms all use templates heavily (and eschew inheritance completely).

    As such, older code (and new code from coders who are older or more conservative) tends to concentrate primarily or exclusively on subtyping. Newer and/or more liberally written code, tends to use templates more. At least in my experience, most reasonably recent code uses a mixture of both. Between the two, I'll normally use subtyping when I have to, but prefer templates when they can do the job.

    Edit: demo code showing polymorphism:

    #include <iostream>
    
    class Person { 
    public:
        virtual void print() const { std::cout << "Person::print()\n"; }
    };
    
    class Student : public Person { 
    public:
        virtual void print() const { std::cout << "Student::print()\n"; }
    };
    
    void blah(const Person &p) { 
        p.print();
    }
    
    int main() { 
        Student s;
        blah(s);
        return 0;
    }
    

    result (cut and pasted from running code above on my computer, compiled with MS VC++):

    Student::print()
    

    So yes, it does polymorphism exactly as you'd want -- and note that in this example, the object in question is allocated on the stack, not using new.

    Edit 2: (in response to edit of question):

    It's true that you can't assign to a reference. That's orthogonal to questions of polymorphism though -- it doesn't matter (for example) whether what you want to assign is of the same or different type from what it was initialized with, you can't do an assignment either way.

    At least to me, it would seem obvious that there must be some difference in capabilities between references and pointers, or there would have been no reason to add references to the language. If you want to assign them to refer to different objects, you need to user pointers, not references. Generally speaking, I'd use a reference when you can, and a pointer if you have to. At least IMO, a reference as a class member is usually highly suspect at best (e.g., it means you can't assign objects of that type). Bottom: if you want what a reference does, by all means use a reference -- but complaining because a reference isn't a pointer doesn't seem (at least to me) to make much sense.