In my code, I want to create a cookie and add it to a shop by sending the cookie to shop constructor as parameter. It adds the cookie but give segmentation fault error.
I get the result:
- Chocolate Cookie 50 180
Segmentation fault (core dumped)!
I cannot find the code part where I am wrong with. Can you help?
main.cpp:
#include <iostream>
#include <string>
#include "Shop.h"
#include "Cookie.h"
using namespace std;
int main(){
Cookie cookie1("Chocolate Cookie", 50, 180);
Cookie cookie2("Cake Mix Cookie", 60, 200);
Shop<Cookie> cookieShop(cookie1);
//cookieShop.Add(cookie2);
cout << cookieShop ;
return 0;
}
Shop.h:
#ifndef SHOP_T
#define SHOP_T
#include <string>
using namespace std;
template<class type>
class Shop;
template<typename type>
ostream& operator<<(ostream& out, const Shop<type>& S){
for(int i = 0; i < S.size; i++)
out << i + 1 << ".\t" << S.list[i] << endl;
}
template<class type>
class Shop{
type *list;
int size;
public:
Shop() { list = 0; size = 0; }
Shop(type t);
~Shop(){ delete[] list; }
void Add(type A);
friend ostream& operator<< <>(ostream& out, const Shop<type>& S);
};
template<class type>
Shop<type>::Shop(type t) : size(0){
list = new type();
list[0] = t;
size++;
}
template<class type>
void Shop<type>::Add(type A){
type *temp = new type[size+1];
for(int i = 0; i < size; i++)
temp[i] = list[i];
delete[] list;
temp[size] = A;
list = temp;
size++;
}
#endif
Cookie.h:
#ifndef COOKIE
#define COOKIE
#include <string>
using namespace std;
class Cookie{
string name;
int piece;
float price;
public:
Cookie(string = "", int = 0, float = 0);
friend ostream& operator<<(ostream& out, const Cookie& C);
};
#endif
Cookie.cpp:
#include "Cookie.h"
#include <iostream>
#include <string>
using namespace std;
Cookie::Cookie(string n, int pi, float pr){
name = n;
piece = pi;
price = pr;
}
ostream& operator<<(ostream& o, const Cookie& C){
o << C.name << "\t" << C.piece << "\t" << C.price;
}