Absolute newbie to c++ (and oop) as well.
Just wanted to ask how to return an object from a list (if it exists), by passing a single id to a getter.
My code is as follows:
class Customer
{
private:
unsigned int custNo;
std::string name;
std::string address;
/* .. */
}
class Store
{
private:
std::string storeName;
std::list<Customer *> customerBase;
std::list<Product *> productStock;
std::list<Sale*> sales;
public:
Store(std::string storeName); // constructor
std::string getStoreName();
Customer & getCustomer(unsigned int custId); //METHOD IN QUESTION
/*..*/
// Constructor
Customer::Customer(std::string name, std::string address)
{
//ctor
}
//
Customer & Store::getCustomer(unsigned int custId){
}
I know this might be a farily basic question. Still I would very much appreciate the help. Thanks in advance!
Pointer is the first thing that you should think when you see "if it exists". This is because the only representation of an object in C++ that can be optional is a pointer. Values and references must always be present. Therefore, the return type of your function should be
Customer*
, notCustomer&
:If you need fast retrieval by an
id
, use amap<int,Customer*>
orunordered_map<int,Customer*>
. You could do it with a list, too, but the search would be linear (i.e. you would go through the entire list in the worst case).Speaking of pointers, if you must store pointers to
Customer
objects, assuming that the objects themselves are stored in some other container, you may be better off usingshared_ptr<Customer>
in both containers, to simplify resource management.