I come from a Java background and I recently started to learn Qt with C++. While doing some coding a few doubts about objects creation and members declaration have come to me:
Supposing I have a class declared as follows:
ClassA.h:
class ClassA {
private:
MyObject myObj;
QString *declaredArray;
QSharedPointer<MyObject> obj;
public:
void setInfo();
}
ClassA.cpp
void ClassA::setInfo() {
declaredArray = new QString[5];
obj = QSharedPointer<MyObject>(new MyObject, doDeleteLater);
}
What happened in the header where MyObject myObj; was declared? Was an object of type MyObject created in the stack and assigned to variable myObj using a constructor which takes no arguments? Or only an empty variable prepared to store a MyObject object was declared?
In ClassA.cpp how would I assign a new object created in the stack to myObj variable?
declaredArray is an array of ints created in the heap, should I add a destructor with a delete declaredArray; to avoid memory leaks?
What happened in the header where QSharedPointer<MyObject> obj; was declared? Was an empty pointer to MyObject created? Is the assignment in ClassA.cpp (obj = QSharedPointer<MyObject>(new MyObject, doDeleteLater);) correct?
There will be space for
myObj(of the size ofMyObject) whereverClassAis allocated (ifClassAis allocated on the stack, space formyObjwill be on the stack).If an applicable default constructor exists for
MyObject, and either:ClassA() : myObj(), declaredArray(NULL), obj(NULL) { }... then
myObjwill be initialized to the default value (MyObject()).Also note that any heap-allocated memory you create with
newshould be deallocated withdeleteon destruction. Therefore, you should also have a destructor:Thanks to RAII, you won't need to destruct
myObjandobjif explicitly initialized in theClassAconstructor. If they are not, however, then you will need to explicitly destruct them (e.g., in the case of the shared pointer, decrement the counter).To answer your other questions explicitly:
myObjwill only be default-constructed (constructed with a constructor that takes no arguments) if the default constructor exists and has been created (implicitly or explicitly).If
myObjwas valid, thenmyObj = MyObject(...);(without anewkeyword) would suffice. Note that this would calloperator=()(the assignment operator) onmyObj, somyObjneeds to be already defined for this to be fully defined behavior. If it is already default constructed, thenmyObj = MyObject(...);is fine.Yes, you should, as shown above.
The documentation for QSharedPointer shows that its default constructor is a
QSharedPointerpointing toNULL. If you have a default constructor which is appropriately calling the default constructor for the members, then you should be fine.A properly constructed (e.g. default or non-default constructed, but initailized)
QSharedPointercan be assigned to using the assignment operator as you showed:(obj = QShardPointer<MyObject>(new MyObject)).