In Java, generics are invariant; you would need to use bounded wildcards to achieve covariance or contravariance. To do what you want, in Java it would need to be declared like this:
List<? extends Base> baseArray;
List<Child> childArray;
baseArray = ChildArray;
By using the ? extends
wildcard, Java prevents you from adding any elements other than null
into the list using the reference of type List<? extends Base>
, since the wildcard stands for an unknown type and you don't know that what you're adding is an instance of that type. You can only get elements out of it.
(It is true that arrays in Java are covariant, but it seems like you are talking about generic containers here, not arrays.)
C++ doesn't have bounded wildcards. The most common use case of bounded wildcards in Java is when you accept a collection parameter that the method only needs to read out of, so it doesn't really care about the exact type argument, only that the type argument is a particular type or its subtype:
void printListOfBase(List<? extends Base> list) {
// you can call methods of Base on the elements of list
}
In C++, you can achieve the same thing with templates without needing any bound, because C++ template instantiations are "duck-typed". Unlike in Java, where a generic class or method is only compiled once and you must prove to the compiler when compiling the class/methd that what you are doing is type-safe giving the bounds, in C++, a templated class or function is compiled separately for each instantiation (i.e. each type argument used), and so the compiler can check when compiling a specific instantiation whether the type works or not, without needing bounds specified beforehand:
void printListOfBase<T>(std::vector<T> list) {
// you can call methods of Base on the elements of list
// and it will compile as long as T has such a method
}
As for your particular case of having a local variable of a wildcard-parameterized type, that is much less common and there is no direct equivalent for it in C++.
std::vector
isList<T>
which is invariant so your example would not compile.