!! Note: I edited the question many times after the answers. But the question below is the first question and the first answer is a helpful answer. Please do not confuse by some comments. They are written after I changed my question many times.
I have a Shop template class and have class Cookie. Shop is a list that keeps cookies named cookieShop. Shop cotr can take one cookie as its parameter and more can be added by Add method of the Shop template class.
I'm creating two cookies. One is added by shop cotr, and second by add method. Even if I dont write codes in add method, second cookie is added to shop list. I tried to understand why it does that but could not.
Here is my code:
//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;
string name;
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 = &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();
Cookie(string n, int pi, float pr);
friend ostream& operator<<(ostream& out, const Cookie& C);
};
#endif
//Cookie.cpp
#include "Cookie.h"
#include <iostream>
#include <string>
using namespace std;
Cookie::Cookie() {}
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;
}
//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 <<endl;
return 0;
}
As you can see the codes in Add method are commented. How it adds the second cookie?
When compile (gcc main.cpp Cookie.cpp) and run it (./a.out) it gives the lines below:
Note: Im new at stackoverflow. If I have wrong behaviors. Please tell :)
Here:
template<class type>
Shop<type>::Shop(type t) : size(0){
list = new type;
list = &t;
size++;
}
The variable t
is local to this function. You make list
a pointer to that variable. When the function terminates, the variable passes out of scope, the Shop is left holding a dangling pointer, and you get undefined behavior.