Reputation: 207
If I have a var
vector<myClass> myVector;
Is it already initialized?, ie, may I add (push_back) inmediately elements or I should call the constructor in the following way?
myVector = vector<myClass>();
On the other hand, is it the same std::vector<myClass>
and vector<myClass>
?
Upvotes: 2
Views: 104
Reputation: 4519
The notation
MyClassType a;
actually calls MyClassType
's default constructor, if it has one. So yes, a vector
is already initialized and ready to use.
Your second snippet:
myVector = vector<myClass>();
Actually creates a new, temporary vector
, which is default constructed, and then calls myVector
's copy assignment operator operator=()
.
In this regard, C++ is different from many other languages. For example, in Java, you'd need to do MyClassType a = new MyClassType()
. This is not necessary in C++. Whenever you declare a value of class type with automatic storage1, the object is automatically default constructed. This is also true for class members. Let's say you have:
class A {
std::vector<int> m_myVector;
};
Then there is no need to initialize m_myVector
- it's done automatically whenever you instantiate an object of class A
.
It's different when you allocate objects on the heap:
// Note: DON'T use raw pointers in actual code - use smart pointers instead.
// Just for illustration purposes.
// This is just a pointer to an A, it's not yet initialized.
A* myA;
myA = new A();
// now myA points to a heap allocated, default constructed A object.
// Note that you can omit the default constructor's `()` and just write:
myA = new A;
Heap allocating an object is actually closer to what Java does under the hood. Anyway, when writing proper C++, you rarely need to heap allocate, and you wouldn't ever do it with a vector
.
1 Automatic storage: Put simply, anything you create in C++ without using new/delete
or similar.
Upvotes: 1
Reputation: 254741
Is it already initialized?
Yes (assuming this is std::vector
). As with any sane class, all its constructors (including the default constructor used here) put it into a well-defined state. At this point, it's a valid, empty vector.
I should call the constructor in the following way?
That's not calling the constructor (at least, not on myVector
). Constructors are called automatically during object initialisation; there's no way to call it a second time. This creates another empty vector, then copy-assigns it to myVector
.
On the other hand, is it the same std::vector and vector?
Presumably, this is std::vector
, dumped into the global namespace with an evil using namespace std;
. To avoid doubt, confusion and potential amibiguity, you should avoid doing that, remove any rogue using-directives, and always refer to it as std::vector
.
Upvotes: 5
Reputation: 9411
In this case
vector<myClass> myVector;
there is no need to call default constructor separately.
You can call push_back
and other methods.
Upvotes: 2