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.