Reputation: 109
I am trying to add a string to vector but the program crashes while adding the string.Vector is declared in a seperate header file called customer.hpp and the implementation is in customer.cpp. In that file i am facing problem with addProductTocart function. Thanks in advance
Customer.hpp
#ifndef CUSTOMER_HPP
#define CUSTOMER_HPP
#include "Product.hpp"
class Customer
{
private:
std::vector<std::string> carts;
std::string name;
std::string accountID;
bool premiumMember;
public:
Customer(std::string n, std::string a, bool pm);
std::string getAccountID();
std::string cusname();
//std::vector<std::string> getCart();
void addProductToCart(std::string);
bool isPremiumMember();
void emptyCart();
};
#endif
This is the function that i am passing string from
void Store::addProductToMemberCart(std::string pID, std::string mID)
{
cout<<"adding to cart"<<endl;
Customer *c=Store::getMemberFromID(mID);
c->addProductToCart(pID);
}
now for the crashing part. while adding the string to the vector the program crashes
void Customer :: addProductToCart(std::string ID)
{
carts.push_back(ID);
}
Edit:
Customer* Store:: getMemberFromID(std::string id) {
for(int i = 0; i < members.size(); i++) {
Customer c = members.at(i);
if(c.getAccountID() == id) { return &c; }
}
return NULL;
}
Upvotes: 0
Views: 179
Reputation: 20264
it seems that Customer *c=Store::getMemberFromID(mID);
return an invalid pointer (nullptr for example). Check it using your debugger.
Since you did not provide the implementation of Store::getMemberFromID(mID)
, we can not help more than that.
Edit:
After you have provided the implementation of getMemberFromID
, It is obvouise that you are returning a pointer to stack allocated object that will be freed when it goes out of scope. You simply have undefined behaviour in your code.
How to solve this? you may change the implementation to something like this:
Customer* Store:: getMemberFromID(std::string id) {
for(int i = 0; i < members.size(); i++) {
Customer& c = members.at(i);
//______^_______
if(c.getAccountID() == id) { return &c; }
}
return NULL;
}
Anyway, this is not a good solution. Please consider redesigning your problem in a better way.
Upvotes: 1