Hi, I am still reasonably new at this and i've come up against yet another problem. So far i haven't had trouble creating classes and objects and using member functions of specific objects in main, but on this program i made, i need a member function of an object to be called from another function outside main.
This is a simple program that asks you to define stock of your three shops at the start and then you can sell stuff from any shop.
Code:
#include <iostream>
int choicea();
int choiceb();
int choicec();
class shop
{
private:
int books;
int pencils;
public:
int init()
{
std::cout<<"How many books?: ";
std::cin>>books;
std::cout<<"And how many pencils?: ";
std::cin>>pencils;
}
int sellb()
{
int d;
std::cout<<"How many books would you like to sell?: ";
std::cin>>d;
books=-d;
}
int sellp()
{
int f;
std::cout<<"How many pencils did you sell?: ";
std::cin>>f;
pencils=-f;
}
int display()
{
std::cout<<"There are "<<books<<" books and " <<pencils <<" pencils\n";
}
};
int main()
{
char in;
shop shop1;
shop shop2;
shop shop3;
std::cout<<"Initialize your stock for your 3 shops\n";
shop1.init();
shop2.init();
shop3.init();
std::cout<<"What would you like to do?\nA.Sell books\nB.Sell Pencils\nC.Quit\n";
std::cin>>in;
switch(in)
{
case 1:
choicea();
break;
case 2:
choiceb();
break;
case 3:
choicec();
break;
default:
std::cout<<"Not valid, Please choose again: ";
}
return 0;
}
int choicea()
{
char a;
std::cout<<"What shop are you selling from? A.Shop 1\nB.Shop 2\nC.Shop 3: \n";
std::cin>>a;
switch(a)
{
case 1:
shop1.sellb() ;
break;
case 2:
shop2.sellb();
break;
case 3:
shop3.sellb();
break;
default:
std::cout<<"Not valid, Please choose again: ";
return 0;
}
}
int choiceb()
{
char a;
std::cout<<"What shop are you selling from? A.Shop 1\nB.Shop 2\nC.Shop 3: \n";
std::cin>>a;
switch(w)
{
case 1:
shop1.sellp() ;
break;
case 2:
shop2.sellp();
break;
case 3:
shop3.sellp();
break;
default:
std::cout<<"Not valid, Please choose again: ";
return 0;
}
}
int choicec()
{
return 0; //figure out how to quit!!!!
}
I thought member functions were global but it seems their only loacal to where the object is created,does that make sense?
I know there's probably way better ways of doing this but its just practice to get the hang of objects.
Could someone please tell me how to call a member function of an object from a function.
Thanks
P.S These were some of the 10 error msgs
error C2065: 'shop1' : undeclared identifier
error C2228: left of '.sellb' must have class/struct/union type
I'm guessing i'm going to have to learn what unions are