suppose i'm implementing a polymorphic tree data structure that can take on data of any type...
Tree<Int> or Tree<String> or Tree<Object>
but I'm implementing it in C++....how would I specify that the tree can contain an arbitrary type similar to generics in Java
also is there an equivalent of Java's Object object in C++ in which all objects in C++ inherits Object
A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
The nearest equivalent of Java's generic is template in C++. Its not equivalent as such, if strictly speaking. But that is what you've in C++. So to suit your need, you've to work a little bit so that you can write equivalent code in C++.
Here're few links to some articles that compare C++ template with Java generics:
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