Java – Why doesn’t C++ support covariance in STL containers like C# or Java

ccollectionsjavatemplates

The Covariance and Contravariance feature is well supported in C# and Java collections. However C++ doesn't support them in their STL containers. Why is it so?

For example the below code will compile in C# and Java but not in C++. (The syntax will have to be translated to the specific language though)

class Base
{

};

class Child : public Base
{

};

int main()
{
    std::vector<Base*> baseArray;
    std::vector<Child*> ChildArray;

    baseArray = ChildArray;

    return 0;
}

Best Answer

The reason is the underlying object and memory models.

To simplify the reasoning:

  • In java and C#, objects of a class are managed by reference. Containers do not store directly the object value but a reference that says where to find the value. It is therefore technically easy to mix objects of different types in the same container (polymorphism) or to use the container for objects of covariant types. The only constraint is the language semantics. This facilitates significantly the implementation of covariant containers.

  • In C++, objects are managed by value, following the rules of its memory model, which basically requires that objects of a given type a stored within a fixed size (which of course can contain pointers to elements having a dynamic size). A container therefore has to know the type of its objects at compile-time. Unfortunately (or not) C++ also allows for separate compilation. So when you compile a container for Animals in one translation unit, the compiler might not know the size of a Cat (which might not even yet be developed). All this makes it extremely difficult to implement covariance in the language.

Interestingly, in C# you can have objects that are managed by value (in the case of a struct). But as this Microsoft documentation and this SO question explain, variance only applies to reference types.

Of course, all this is simplified explanations and language-lawyers could argue on some details, but i hope it helps to grasp the idea.