Deleting objects in C++ explicitly - c++

I have a class myclass.
In the main function, I create objects of type myclass in every iteration and want to delete them after each iteration. I have not created the objects dynamically. Can I delete the them explicitly because I don't need them after the iteration gets over.
class myclass{
int value;
void do_function();
};
int main()
{
for(int i=0;i<count;i++)
{
myclass obj;
obj.do_function();
}
}
The object obj is not needed after one iteration, but the memory is still there. How can I free that memory?

You don't have to delete them explicitly, because as you have created them myclass obj; they are created on stack and deleted after each iteration.
When the program reaches the first curly brace after the instantiation on stack of an object it deletes it, in your case:
myclass obj;
obj.do_function();
} // Here the obj is deleted
Here are some examples and explanations of how stack is working, versus heap, to let you understand better when you need to free memory yourself, and when you don't.
Note: I have used notions of stack and heap only to suggest how objects are handled relatively to their lifetime like when an object from stack should be freed after it leaves the scope, and an object of heap lives until it's explicitly freed. As mentioned in comments, these notions are not considered in standard C++ because the programs can run in an environment which does not support these type of memory. Although the compiler respects these rules for a C++ program.

myclass obj; will already be deleted automatically after each iteration of the loop.
How can I free that memory?
You don't need to.

Short answer is that you don't need to.
Here's a quick example:
class myClass {
public:
myClass() { cout << "Hello!" << endl; }
~myClass() { cout << "Goodbye!" << endl; }
void do_function() { cout << "Something" << endl; }
};
int main() {
for (int i=0; i<3; ++i) {
myClass obj;
obj.do_function();
}
}
Output:
Hello!
Something
Goodbye!
Hello!
Something
Goodbye!
Hello!
Something
Goodbye!
You are allocating obj on the stack. Whenever your program goes out of scope, the memory automatically gets released from the stack.
You create a scope for every iteration of a for loop. Or the inner curly brace:
for (int i=0; i<3; ++i) { <-- Right there
And obj goes out of scope:
obj.do_function();
} <-- Right here

If you don't create an object dynamically, the object is created on stack and it is deleted when the closing bracket, that defines its scope, is seen. You can have your own opening and closing brackets to restrict the scope of a variable. This would be helpful to just free memory from unnecessary variables. For example
for(...)
{
//do something
{
myclass obj;
/// use obj here
}//obj is deleted from stack
//do something which doesnt require myclass obj
}

Related

How to create an Instance of a class on heap memory

A class type called "Pair" has already been defined for you. You need to write a function called pairFactory that creates an instance of Pair on the heap. Do not create the object on the stack. Then, your function needs to return a pointer to that created object.
I have written the code for pairFactory. It seems to run, but I get an InfraError.
Please help me find my mistake.
Also, I need to create the object in heap memory.
#include <iostream>
// This class Pair has already been defined for you.
// (You may not change this definition.)
class Pair {
public:
int first, second;
void check() {
first = 5;
std::cout << "Congratulations! The check() method of the Pair class \n has executed. (But, this isn't enough to guarantee \n that your code is correct.)" << std::endl;
}
};
Pair *pairFactory() {
//
Pair P;
P.check();
// (You can use as many lines as you want.)
return &P;
}
// Your function should be able to satisfy the tests below. You should try
// some other things to convince yourself. If you have a bug in this problem,
// the usual symptom is that after you submit, the grader will crash with a
// system error. :-)
int main() {
Pair *p;
p = new pairFactory();
// This function call should work without crashing:
p->check();
// Deallocating the heap memory. (Assuming it was made on the heap!)
delete p;
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
return 0;
}
You've got it backwards. Your factory needs to allocate on the heap. What you're doing is returning the address of a function-local object that doesn't exist anymore.
Pair *pairFactory() {
return new Pair;
}
And then in your main function:
Pair *p = pairFactory();
You return reference to local variable here.
Pair *pairFactory() {
Pair P;
P.check();
return &P; // Dangling pointer
}
So you have dangling pointer, once you leave the function.
You have to call new.
Pair *pairFactory()
{
return new Pair{};
}
main may look like:
int main() {
Pair* p = pairFactory();
// This function call should work without crashing:
p->check();
// Deallocating the heap memory. (Assuming it was made on the heap!)
delete p;
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
Better to use smart pointer to not have to manage memory yourself:
std::unique_ptr<Pair> pairFactory()
{
return std::make_unique<Pair>();
}
int main() {
auto p = pairFactory();
p->check();
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
You did exactly as you were told not to do:
Pair *pairFactory() {
Pair P; // <----- creates an instance of Pair on the stack
…
}
The intention of this exercise likely was to test your knowledge on the new operator. See here https://en.cppreference.com/w/cpp/memory/new/operator_new
The function
Pair *pairFactory() {
return &P;
}
returns a pointer to memory on the local stack, which is destroyed / invalid as soon as it returns to main().
The issue with your code is that it returns a pointer that points to nothing as P only exists till the value of p is returned, as stored in heap memory. Using new keyword will allocate the memory in heap and will return a pointer to the value.
Pair *pairFactory() {
Pair P;
P.check();
return &P;
}

why is the dynamically allocated object going out of scope outside the function?

I want to allocate objects on the heap according to a string entered by the user but I cannot access the pointers or objects outside the function although they are on the heap. As well, I tried to allocate them using unique pointers but I'm still getting an error saying "not declared" etc.
How can I create these objects, a user can create eight objects concurrently with spaces between the words. (e.g. "Avalanche Toolbox Paperdoll" and so on)?
string user_input;
getline(cin, user_input);
istringstream iss(user_input);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
for(int i=0; i<8; i++)
{
if(vec.at(i)=="Avalanche")
{
Avalanche *avalanche = new Avalanche(5);
std::unique_ptr<Avalanche> ptr(new Avalanche(5)); // even tried using unique pointer.
cout<<"Avalanche: "<<avalanche->c_game<<endl;
}
else if(vec.at(i)=="Bureaucrat")
{
Bureaucrat *bureaucrat = new Bureaucrat(5);
cout<<"Bureaucrat: "<<bureaucrat->c_game<<endl;
}
else if(vec.at(i)=="Toolbox")
{
Toolbox *toolbox = new Toolbox(5);
cout<<"Toolbox: "<<toolbox->c_game<<endl;
}
else if(vec.at(i)=="Crescendo")
{
Crescendo *crescendo = new Crescendo(5);
cout<<"Crescendo: "<<crescendo->c_game<<endl;
}
else if(vec.at(i)=="Paperdoll")
{
Paperdoll *paperdoll = new Paperdoll(5);
cout<<"Paperdoll: "<<paperdoll->c_game<<endl;
}
else if(vec.at(i)=="FistfullODollars")
{
Fistfullodollars *fistfullodollars = new Fistfullodollars(5);
cout<<"FistfullOdollars: "<<fistfullodollars->c_game<<endl;
}
}
cout<<ptr.c_game<<endl; // give an error not declared
Your object lifetime is limited to it's scope. In your case, the scope is within two closest {}. You need to remember that when you have a (smart)pointer to allocated memory, you actually have TWO objects - one is your (smart) pointer, and the other is the object the pointer points to. When the pointer goes out of scope, you can not reference the actual object by this pointer anymore. And if there is no other pointer pointing to this object, the object is lost forever, and you have is a classic example of so called memory leak - there is an object somewhere there, but is unaccessible, and the memory occupied by it is lost and can not be reused.
Think about it in a following way - you have a book and a library card. The book is somewhere in the vast storage, and unless you know where to look (using library card) you will never find it. So if you lost all copies of your library cards, the book is as good as lost to you - though it is obviously somewhere there.
The answer is, that your objects created are not deleted, since you have created them on the heap, as you pointed out, but the pointer variables go out of scope. The solution is, to put the declaration outside of the scopes and do the assignment in the scope:
string user_input;
getline(cin, user_input);
istringstream iss(user_input);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
Bureaucrat *bureaucrat;
Toolbox *toolbox;
Crescendo *crescendo;
Paperdoll *paperdoll;
Fistfullodollars *fistfullodollars;
for(int i=0; i<8; i++)
{
if(vec.at(i)=="Avalanche")
{
Avalanche *avalanche = new Avalanche(5);
std::unique_ptr<Avalanche> ptr(new Avalanche(5)); // even tried using unique pointer.
cout<<"Avalanche: "<<avalanche->c_game<<endl;
}
else if(vec.at(i)=="Bureaucrat")
{
bureaucrat = new Bureaucrat(5);
cout<<"Bureaucrat: "<<bureaucrat->c_game<<endl;
}
else if(vec.at(i)=="Toolbox")
{
toolbox = new Toolbox(5);
cout<<"Toolbox: "<<toolbox->c_game<<endl;
}
else if(vec.at(i)=="Crescendo")
{
crescendo = new Crescendo(5);
cout<<"Crescendo: "<<crescendo->c_game<<endl;
}
else if(vec.at(i)=="Paperdoll")
{
paperdoll = new Paperdoll(5);
cout<<"Paperdoll: "<<paperdoll->c_game<<endl;
}
else if(vec.at(i)=="FistfullODollars")
{
fistfullodollars = new Fistfullodollars(5);
cout<<"FistfullOdollars: "<<fistfullodollars->c_game<<endl;
}
}
cout<<ptr.c_game<<endl; // give an error not declared
ptr is declared on the stack, it's the object it's pointing at which is delete bound.
when if(vec.at(i)=="Avalanche") {} is over, ptr (which is stack allocated) gets out of scope and no longer accesible.
Even if you allocate your object dynamically you still need a pointer variable to keep track of where that memory is. Your ptr variable is destroyed at the end of the enclosing braces.
I'm guessing all your classes Avalanche, Bureaucrat... inherit from some base class with a c_game member variable. Perhaps something a bit like this:
struct MyBase {
virtual ~MyBase(){} // This is important!
MyBase(std::string c_game) : c_game(c_game) {}
std::string c_game;
};
struct Avalanche : public MyBase {
Avalanche(int num) : MyBase("Avalanche"), num(num) {}
int num;
};
struct Fistfullodollars : public MyBase {
Fistfullodollars(int num) : MyBase("Fistfullodollars"), num(num) {}
int num;
};
//...
In order to keep track of these dynamically allocated objects you could construct a container of (smart) pointers to this base class:
std::vector<std::unique_ptr<MyBase>> objects;
for(size_t i=0; i!=vec.size(); i++)
{
if(vec.at(i)=="Avalanche")
{
objects.push_back(std::make_unique<Avalanche>(5));
std::cout<<"Avalanche: "<<objects.back()->c_game<<"\n";
}
else if(vec.at(i)=="FistfullODollars")
{
objects.push_back(std::make_unique<Fistfullodollars>(5));
std::cout<<"FistfullOdollars: "<<objects.back()->c_game<<"\n";
}
//...
}
for (const auto& ptr : objects)
{
std::cout << ptr->c_game << "\n";
}
Live demo.

Object instantiation methods in C++

What is the difference between these two instantiation and method call types?
Take this code for example:
class Test
{
public:
Test(int nrInstance)
{
std::cout << "Class " << nrInstance << " instanced " << std::endl;
}
~Test() { }
int retornaValue()
{
return value;
}
private:
const int value = 10;
};
int main(int argc, char *argv[])
{
Test *test1 = new Test(1);
Test test2(2);
std::cout << test1->retornaValue() << std::endl;
std::cout << test2.retornaValue() << std::endl;
return 0;
}
From what ive read, using the first way, the variable is allocated in the heap, and the second, in the stack, but arent both inside the Main scope, and being deallocated after the function exits?
Also, calling methods is different in both examples, why?
Your right that both variables are in the Main scope and deallocated after the function exits, but in the first case it is the Test* value that is deallocated, not the Test instance itself. Once the pointer is deallocated, the class instance is leaked. In the second case, the Test instance is on the stack, so the instance itself is deallocated.
Also, calling methods is different in both examples, why?
Unless overloaded, foo->bar is equivalent to (*foo).bar. The calling syntax is different because in the first case, test1 is a pointer to an instance, and in the second, test2 is an instance.
but arent both inside the Main scope, and being deallocated after the
function exits?
No not at all... *test1 will not be deallocated until you call delete on it.
but arent both inside the Main scope, and being deallocated after the function exits?
The stack instance is unwound as the scope is closed, and thus deallocated. The pointer is as well, but the object it points to is not. You must explicitly delete instances allocated with new.
In the first example, you are creating both a pointer to the object on the stack, and the object itself on the heap.
In the second example you are creating the object itself on the stack.
The syntax difference is the difference between calling a function through a pointer and calling it on an object directly.
You are wrong about the first example being cleaned up, you need a delete before the pointer goes out of scope or you have what is known as a memory leak. Memory leaks will be cleaned up by the OS when the program exits, but good practice is to avoid them.
You've clearly stated the difference in your question, one is on the stack, and one is on the heap. And yes, when main() exits, it will be deallocated. Now let's take a different approach.
#include <iostream>
using namespace std;
class MemoryLeak{
private:
int m_instance
public:
MemoryLeak(int i) : m_instance(i)
{ cout << "MemoryLeak " << i << " created.\n"; }
~MemoryLeak() { cout << "MemoryLeak " << m_instance << " deleted.\n"; }
};
void makeMemoryLeak(){
static int instance = 0
MemoryLeak mem1(++instance);
MemoryLeak* mem2 = new MemoryLeak(++instance);
}
int main(){
for(int x = 0; x < 10; ++x){
makeMemoryLeak();
cout << endl;
}
cin.get(); // Wait to close
return 0;
}
You will see 20 "New MemoryLeak created." lines but only 10 "MemoryLeak deleted" lines. So those other 10 instances are still in memory until you close the program. Now let's say that that program never shuts down, and MemoryLeak has a size of 20 bytes. and makeMemoryLeak() runs once a minute. After one day, or 1440 minutes, you'll have 28.125 kb of memory that is taken up, but you have no way to access.
The solution would be to change makeMemoryLeak()
void makeMemoryLeak(){
MemoryLeak mem1;
MemoryLeak* mem2 = new MemoryLeak();
delete mem2;
}
Regarding what gets created and destroyed:
struct Test {};
void func()
{
// instantiate ONE automatic object (on the stack) [test1]
Test test1;
// Instantiate ONE automatic object (on the stack) [test2]
// AND instantiate ONE object from the free store (heap) [unnamed]
Test* test2 = new Test; // two objects!!
} // BOTH automatic variables are destroyed (test1 & test2) but the
// unnamed object created with new (that test2 was pointing at)
// is NOT destroyed (memory leak)
if you dont delete Test1 (Test*) before coming out of main, it will cause memory leak.

Appropriate destruction of certain class members

I have a class with several pointer members that can be reallocated. When I use the LoadOBJ() function, I'm supposed to replace the already held data but I'm having trouble with garbage collection. Below is some code.
class Object3d{
public:
int nVertex;
int nFace;
int nVertexNormal;
Vector3d *vertex;
Vector3d *vertexNormal;
Face3d *face;
void LoadOBJ(char*);
Object3d():nVertex(0), nFace(0), vertex(NULL), face(NULL){}
Object3d(char*);
~Object3d(){}
};
Face3d:
struct Face3d{
int nFaceV;
int *iVertex;
int *iVertexNormal;
Face3d():nFaceV(0){}
};
Everytime I load a new object with the LoadOBJ() function, I want to delete the previously allocated memory, rather than just use new and leak previously allocated memory.
I'm not sure how to do this. This is what I thought of for now:
void *vGarbage, *vGarbage2,
*fGarbage,
*iGarbage, *iGarbage2;
//nFace is the previous number of faces; in the case of a new object, it's 0
for(int i=0; i<nFace; i++)
{
iGarbage=face[i].iVertex;
iGarbage2=face[i].iVertexNormal;
delete[] iGarbage;
delete[] iGarbage2;
}
vGarbage=vertex;
fGarbage=face;
vGarbage2=vertexNormal;
delete[] vGarbage;
delete[] vGarbage2;
delete[] fGarbage;
The above code runs everytime I use LoadOBJ(), but there still is memory leak. I'm also wondering if this is the right way to do it?
To clarify where the problem/question is: why do I still have memory leak? And, is there better/cleaner way to delete the previously allocated memory?
Check out C++11's smart_pointers, they provide the ability of allocating memory which, when the object goes out of scope, will be freed automatically.
#include <memory>
#include <iostream>
struct Foo {
Foo() { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
};
struct D {
void operator()(Foo* p) const {
std::cout << "Call delete for Foo object...\n";
delete p;
}
};
int main()
{
{
std::cout << "constructor with no managed object\n";
std::shared_ptr<Foo> sh1;
}
{
std::cout << "constructor with object\n";
std::shared_ptr<Foo> sh2(new Foo);
std::shared_ptr<Foo> sh3(sh2);
std::cout << sh2.use_count() << '\n';
std::cout << sh3.use_count() << '\n';
}
{
std::cout << "constructor with object and deleter\n";
std::shared_ptr<Foo> sh4(new Foo, D());
}
}
Output:
constructor with no managed object constructor with object Foo... 2 2
~Foo... constructor with object and deleter Foo... Call delete for Foo
object... ~Foo...
(http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr)
Remember that for each new a delete should be called when freeing memory. Local pointers can be dangerous if they get destroyed and you didn't free memory before that point.
The RAII paradigm in object-oriented C++ has been designed specifically to make resource management (and also memory management) easy.
If disaster has already been done, you can clean your code up with something like http://deleaker.com/ or equivalent memory leak-seeker software.
Also: if you can't use C++11 or you can't use a C++11-supporting compiler, take a chance of implementing smart pointers yourself, it shouldn't be too hard and will surely help your memory problems.
I understand you want to free the memory occupied by Object3d::vertex, Object3d::vertexNormal and Object3d::face before reasigning these members. First, you should provide a custom destructor for your Face3d so that you no longer need to care for it's members in the containing class. That is:
face3d::~face3d() {
if (iVertex) delete[] iVertex;
if (iVertexNormal) delete[] iVertexNormal;
}
In your Object3d class, you can use a dedicated clean-up function:
void Object3d::cleanup() {
if (face) delete[] face;
face = nullptr;
if (vertex) delete[] vertex;
vertex = nullptr;
if (vertexNormal) delete[] vertexNormal;
vertexNormal = nullptr;
nVertex = 0;
nFace = 0;
nVertexNormal = 0;
}
Btw, In the destructor Object3d::~Object3d() you must call that function as well.
This question might answer yours. I think that you have to cast the void pointer to a specific one, like int*, to make it work. But the behaviour is highly dependent of the compiler you use.
edit: the advice of using smart pointers is probably the easiest and safest way of solving your problem.
Use std::vector instead of manually managed arrays:
struct Face3d{
int nFaceV;
std::vector<int> iVertex;
std::vector<int> iVertexNormal;
Face3d():nFaceV(0){}
};
class Object3d{
public:
std::vector<Vector3d> vertex;
std::vector<Vector3d> vertexNormal;
std::vector<Face3d> face;
void LoadOBJ(char*);
Object3d():nVertex(0), nFace(0), vertex(NULL), face(NULL){}
Object3d(char*);
~Object3d(){}
};
This frees you from the burden to write destructors. As already said above, this is exemplifies the RAII pattern in C++ which should be used instead of manual resource management.
As a general comment, public data members are almost always a bad idea because it breaks encapsulation. Object3d should provide some services to clients and keep its internal private.

Do I have to delete this object? (if I don't intend to be ever deleted)

I have programmed a little software and wanted to create a new object on the heap. In the class member function I thus have
void gShop::CreateCustomer(int type, int number)
{
vSlot[number] = new gCustopmer(type);
vSlot[number]->itsContactToShop=itsShopNumber;
vSlot[number]->itsNumber=number;
}
where vSlot is a vector of pointers to customer objects. I have a (here: abbreviated) class gShop, in essence:
class gShop : public gBranch
{
public:
gShop(): vSlot(100){}
~gShop(){}
std::vector <gCustomer*> vSlot;
...
}
and in main I call the member function to create new customers..
vShop[0].CreateCustomer(TYPE_M20, 1);
vShop[0].CreateCustomer(TYPE_F40, **2**);//EDIT:typo previously here. I intend to create customers by reading a file later on.
std::cout<< "1" << vShop[0].vSlot[1]->itsTypeString << std::endl;
std::cout<< "2" << vShop[0].vSlot[2]->itsTypeString << std::endl;
I know that I have created with "new" two objects on the "heap" (if I handle the terminology right - sorry I am quite new to programming without formal education) and I also have two pointers to that objects stored in a vector within the object shop[0].
My question is I heard the saying that for every new there is a delete. Where do I have to delete this object? I am actually not planning on deleting any created shop or customer object in the program.
Secondly, is this code so far okay in terms of not causing memory leaks? I am a bit worried that I created the new object within a member function class, so should I try to implement delete in the destructor to gShop and set the pointer to NULL - in the theoretical case I should ever want to delete shop[0]?
Many thanks.
In the way you have written your code, you should expand you destructor implementation for gShop to iterate over the vector<> vSlot and delete each element. Because you have memory that has to be managed in this way to prevent a memory leak, you are also required to follow the Rule of Three. So, you also need to do something during copy construction (a deep copy), and you have to do something for the assignment operator (cleanup up the vector<> that is about to be copied over, and do a deep copy).
You can avoid these issues, and allow your object to use the default destructor, copy constructor, and assignment operator, by using a smart pointer instead. For example:
std::vector<std::shared_ptr<gCustomer>> vSlot;
When you create an element in the vSlot, you could use make_shared():
vSlot[number] = std::make_shared<gCustopmer>(type);
The smart pointer will delete the memory for you when there are no more references to the memory. If you don't have C++.11 available to you, you can use boost::shared_ptr instead.
The smart pointer will make it so that a copy of your gShop will share the same pointers as the original gShop it copied from. The smart pointer makes that situation okay, since there will not be multiple delete calls on the same memory. However, if you need the deep copy semantics, then you would still need to implement your own copy constructor and assignment operator to make the deep copies.
If you want something that will clean up automatically like a smart pointer, but still give you a deep copy with the default copy constructor and default assignment operator, then you can try to use boost::optional.
If you are using g++ version 4.4 or higher, then you should be able to enable C++.11 features with -std=gnu++0x, or -std=c++0x if you don't want GNU extensions. If you have g++ 4.7 or higher, then the options are -std=gnu++11 or -std=c++11.
Every time you create object with new piece of memory is taken from the heap. Only way to communicate with this memory is via pointer you got from new. When you use delete on that pointer memory is freed and may by used for other purposes. So when you lose pointer you create memory leak.
In your code the right way is:
Start with the vector with null pointers.
When you create object in exact position check pointer. If it is not null you already have object and have to delete it (or maybe throw error)
void gShop::CreateCustomer(int type, int number)
{
if(vSlot[number] != 0) {
delete vSlot[number];
vSlot[number] = 0;
}
vSlot[number] = new gCustopmer(type);
vSlot[number]->itsContactToShop=itsShopNumber;
vSlot[number]->itsNumber=number;
}
When the vector is destroyed you need to free all memory within it. So you destructor will be something like this:
gShop::~gShop() {
for(int i = 0; i < (int)vSlot.size(); ++i) {
delete vSlot[i];
}
}
Yes any memory that is allocated from the heap must be freed!
With the "new" you are allocating memory from the heap that is the sizeof gCustomer.
A good place to deallocate your memory would be in your destructor: ~gShop()
Memory leaks are caused by not deallocating your memory, although once your close your program all the memory is freed automatically.
gShop needs to delete the gCustomer objects that it creates. It can do that in its destructor, eg:
class gShop : public gBranch
{
public:
...
~gShop()
...
};
gShop::~gShop()
{
std::vector<gCustomer*>::iterator iter = vSlot.begin();
std::vector<gCustomer*>::iterator end = vSlot.end();
while (iter != end)
{
delete *iter;
++iter
}
}
Or:
void deleteCustomer(gCustomer *customer)
{
delete customer;
}
gShop::~gShop()
{
std::for_each(vSlot.begin(), vSlot.end(), deleteCustomer);
}
However, you would still have a memory leak. You are storing two separate gCustomer objects in the same vSlot[1] slot of vShop[0], so you are losing track of one of your customers. I suspect you meant to do this instead:
vShop[0].CreateCustomer(TYPE_M20, 1);
vShop[0].CreateCustomer(TYPE_F40, 2); // <-- was previously 1
std::cout<< "1" << vShop[0].vSlot[1]->itsTypeString << std::endl;
std::cout<< "2" << vShop[0].vSlot[2]->itsTypeString << std::endl;
That being said, you should re-think your design and let the STL handle all of the memory management for you, eg:
class gShop : public gBranch
{
public:
std::vector <gCustomer> vSlot;
...
};
void gShop::CreateCustomer(int type)
{
vSlot.push_back(type);
gCustomer &cust = vSlot.back();
cust.itsContactToShop = itsShopNumber;
cust.itsNumber = vSlot.size()-1;
}
vShop[0].CreateCustomer(TYPE_M20);
vShop[0].CreateCustomer(TYPE_F40);
// remember that vectors are 0-indexed
std::cout<< "0" << vShop[0].vSlot[0].itsTypeString << std::endl;
std::cout<< "1" << vShop[0].vSlot[1].itsTypeString << std::endl;
Or:
class gShop : public gBranch
{
public:
std::vector <std::shared_ptr<gCustomer> > vSlot;
...
};
void gShop::CreateCustomer(int type)
{
std::shared_ptr customer = std::make_shared<gCustomer>(type);
customer->itsContactToShop = itsShopNumber;
customer->itsNumber = vSlot.size();
vSlot.push_back(customer);
}
vShop[0].CreateCustomer(TYPE_M20);
vShop[0].CreateCustomer(TYPE_F40);
std::cout<< "0" << vShop[0].vSlot[0]->itsTypeString << std::endl;
std::cout<< "1" << vShop[0].vSlot[1]->itsTypeString << std::endl;