Reputation: 6039
In Java, we can do something like this:
ArrayList arrayList = new ArrayList<String>();
// Notice that String is not mentioned in the first declaration of array
AS OPPOSED TO
ArrayList<String> arrayList = new ArrayList<String>();
How can we something in similar in C++?
Upvotes: 0
Views: 1144
Reputation: 17936
Not in exactly the way you've written.
What you can do is one of the following, depending on what you're actually trying to accomplish:
auto
to automatically adapt to the type: auto = new ArrayList<String>();
. This doesn't give you polymorphism, but it does save you typing the typename on the left hand side.Here's an example of the second approach:
class IArrayList // define a pure virtual ArrayList interface
{
// put your interface pure virtual method declarations here
};
template <typename T>
class ArrayList : public IArrayList
{
// put your concrete implementation here
};
Then, you could say in your code:
IArrayList* arrayList1 = new ArrayList<string>();
IArrayList* arrayList2 = new ArrayList<double>();
...and so on.
Upvotes: 4
Reputation: 959
In c++, you can not use vector array = new vector<string>()
, but in c++11, you can use auto
keyword: auto p = new vector<string>()
, it is the same as vector<string> *p = new vector<string>()
.Hope that my answer can help you.
Upvotes: 2