Reputation: 57
I basically do not know how to ask this question, I am fairly new to c++...anyway my problem is, I am trying to create this vendingmachine class and this user class, the user needs to have access to the insertCoins method and makePurchase methods from vendingMachine.cpp I tried creating an instance of the class vending machine inside the method calls in user.cpp as it is here, but when I try to list the items in vending machine obviously the list is untouched because theinstance I create inside the method calls in user.cpp are just temporary...how would I get a global instance so that I use it within user.cpp while using it within vending machine inside main.cpp...
#include "user.h"
#include "VendingMachine.h"
user::user(){
}
user::~user(){
}
void user::makePurchase(int choice){
VendingMachine vm;
vm.purchaseProduct(choice);
}
void user::insertCoins(double coin){
VendingMachine vm;
vm.insertCoins(coin);
}
~~~~~~~~~~~~~
#include "VendingMachine.h"
#include "machineOperator.h"
#include "user.h"
using namespace std;
int main(){
VendingMachine vm = VendingMachine();
user u = user();
vm.listProducts();
cout << endl;
u.insertCoins(1.0);
u.insertCoins(1.0);
u.makePurchase(2);
vm.listProducts();
cout << endl;
return 0;
}
~~~~~~~~~~~~~~~~~~~
/*
* user.h
*
* Created on: Jan 12, 2014
* Author: Andrey
*/
#ifndef USER_H_
#define USER_H_
class user {
public:
user();
~user();
void makePurchase(int);
void insertCoins(double);
};
#endif /* USER_H_ */
Upvotes: 0
Views: 406
Reputation: 11113
Use a pointer to the VendingMachine in your user and pass it in to the constructor.
user.h
class VendingMachine;
class User {
private:
VendingMachine* vm;
}
user.cc
#include "user.h"
#include "vendingmachine.h"
User::User(VendingMachine* vm): vm(vm) {}
void User::makePurchase(int choice){
vm->purchaseProduct(choice);
}
void User::insertCoins(double coin){
vm->insertCoins(coin);
}
main.cc
#include "VendingMachine.h"
#include "machineOperator.h"
#include "user.h"
using namespace std;
int main(){
VendingMachine vm = VendingMachine();
User u = User(&vm);
vm.listProducts();
cout << endl;
u.insertCoins(1.0);
u.insertCoins(1.0);
u.makePurchase(2);
vm.listProducts();
cout << endl;
return 0;
}
Upvotes: 0
Reputation: 3984
It is natural to assume that a user can purchase from and insert coin to many different vending machines.
void user::makePurchase (VendingMachine &vm, int choice)
{
vm.purchaseProduct(choice);
}
void user::insertCoins (VendingMachine &vm, double coin)
{
vm.insertCoins(coin);
}
Upvotes: 4