Sorry if my last question is very similar, but I have another query of when and if I should use the delete keyword.
Example code.
I initialize a class that has pointer to vector of pointers as their arguments. These objects are assigned memory from the heap. I then pass these objects to my class constructor which is also assigned memory from the heap.
Here is the code: in the main function
//This will also change each loop
vector<A*>* ex1 = new vector<A*>;
vector<B*>* ex2 = new vector<B*>;
vector<C*>* ex3 = new vector<B*>;
for(int i =0; i < 10; i++){
ex1->push_back( new A(i); );
ex2->push_back( new B(i); );
ex3->push_back( new C(i); );
}
MainClass* ex_main = new MainClass(ex1,ex2,ex3);
inside MainClass.cxx
MainClass::MainClass(vector<A*>* ex_A, vector<B*>* ex_B, vector<C*>* ex_C): m_ex_A(ex_A), m_ex_B(ex_B), m_ex_C(ex_C) {}
inside MainClass.h
vector<A*>* m_ex_A;
vector<B*>* m_ex_B;
vector<C*>* m_ex_C;
m_ex1, m_ex2 and m_ex3 have been assigned to the stack, but have been assigned to the pointer to vector of pointers.
Questions.
Do I delete the m_ex_A,B ans C in the destructor of class MainClass (I know I will need to delete the elements in each vector as well) and also the pointer to vector of pointers in the main function?
e.x. in destructor of MainClass (I do something a bit more generic than this, but this is quicker to show )
for(int i = 0; i < m_ex_A->size(); i++){
delete m_ex_A->at(i);
}
delete m_ex_A;
I would then do a similar approach for pointer to vector of pointers ex1, ex2, ex3 in the main function and also delete the main class.
My confusion comes from the fact that m_ex_A,B and C are assigned to the Stack and not dynamically, but they get assigned to dynamic objects?
My guess would be to use delete to m_ex_A,B, C objects as I have dynamically initialized them?
Also what is more efficient using heap memory or stack??
I think I might be using dynamic memory to much...