I've been programming in managed code most of the time and I was interested in going back to C++. Been knocking my head all over the place(on Google) to find an answer. So I started doing the exercises here : http://www.cplusplus.com/forum/articles/12974/ and stumbled lots of errors. I tried the cola machine(second one) and it gave me the idea of making a cola machine and just tried to initialize a list in a Machine with pointers of Drink.
I didn't want to use the Boost library as I wanted to understand how containers worked(especially list).
I will post my code after the questions :
1) I am getting the following error in the line (*it)->getDrinkName()
EXC_BAD_ACCESS on the method : getDrinkName()
in Drink.cpp why is that? Am i not initializing correctly the list with the Drink?
When I try this:
Drink* test = new Drink("Coke");
cout << test->getDrinkName();
it works. Is it my constructor in Drink that is making it crash?
2) Am I suppose to initialize the list in the constructor of Machine? like :
_list = new list<Drink *>();
3) Here is the code :
Drink.h
#include <iostream>
#include <string>
using namespace std;
class Drink
{
public:
Drink(string name);
string getDrinkName();
private:
string _name;
};
Drink.cpp :
#include "Drink.h"
Drink::Drink(string name)
{
_name = name;
}
string Drink::getDrinkName()
{
return _name;
}
Machine.h
#include <iostream>
#include <list>
#include "Drink.h"
using namespace std;
class Machine
{
public:
Machine();
list<Drink*> getList() const;
private:
list<Drink*> _list;
};
Machine.cpp :
#include "Machine.h"
Machine::Machine()
{
}
list<Drink*> Machine::getList() const
{
return _list;
}
main.cpp
#include <iostream>
#include <string>
#include "Machine.h"
using namespace std;
int main () {
Machine* machine = new Machine();
Drink* testCoke = new Drink("Coke");
machine->getList().push_back(testCoke);
std::list<Drink*>::const_iterator it ;
for(it = machine->getList().begin();it!=machine->getList().end();it++)
{
cout << (*it)->getDrinkName();
delete *it;
}
return 0;
}
Thanx in advance!