C++: Class Member Functions
This lesson covers the basic use of functions in a class. These are extremely useful, and luckily for us very similar to normal functions. Here is an example application which helps us create a virtual sandwich:
#include <iostream>
#include <string>
class Sandwich
{
public:
void AddHam(){
ham = true;
}
void AddCheese(){
cheese = true;
}
void AddButter(){
butter = true;
}
bool ham;
bool cheese;
bool butter;
};
int main(){
using namespace std;
string yn1;
string yn2;
string yn3;
Sandwich MySandwich = {false, false, false};
cout << "Do you want ham (Y/N)?" << endl;
cin >> yn1;
if(yn1 == "y" || yn1 == "Y"){
MySandwich.AddHam();
} else if (yn1 == "n" || yn1 == "N"){}
else{
return 0;
}
cout << "Do you want cheese (Y/N)?" << endl;
cin >> yn2;
if(yn2 == "y" || yn2 == "Y"){
MySandwich.AddCheese();
} else if (yn2 == "n" || yn2 == "N"){}
else{
return 0;
}
cout << "Do you want butter (Y/N)?" << endl;
cin >> yn3;
if(yn3 == "y" || yn3 == "Y"){
MySandwich.AddButter();
} else if (yn3 == "n" || yn3 == "N"){}
else{
return 0;
}
cout << "Ham: " << MySandwich.ham << endl;
cout << "Cheese: " << MySandwich.cheese << endl;
cout << "Butter: " << MySandwich.butter << endl;
cout << "This is your order. ";
system("PAUSE");
return 0;
}
DownloadAlthough this code is quite long, its nothing too complicated and just uses old techniques that we have already covered. Reading through it you should now get the idea of class member functions.
Back to C++

