C++ Constructor Car Class - c++

Hi all, I am having some trouble with the below assignment. When I run the code, everything appears to work, but the numbers that I get in the print out are not accurate. Not sure if it is the constructor I have that is set up wrong or what. I've just been banging my head against the wall trying to figure it out. Any help/advice would be much appreciated!
Here is the assignment text:
Car Class Instructions: Write a class named 'Car' that has the following member variables:
year. An int that holds the car's model year.
make. A string object that holds the make of the car.
speed. An int object that holds the car's current speed.
In addition, the class should have the following member functions:
Constructor. The constructor should accept the car's year and make member variables. The constructor should initialize these values to the object's year and make member variables. The constructor should initialize the speed member variable to 0.
Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an object's year, make and speed member variables.
Accelerate. The accelerate function should add 5 to the speed member variable each time it is called.
Brake. THe brake function should subtract 5 from the speed member variable each time it is called. Demonstrate the class in a program that creates a Car object, and then calls the accelerate function five times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function 5 times. After each call to the brake function, get the current speed of the car and display it.
#include <iostream>
#include <string>
using namespace std;
class Car
{
private:
int year;
string make;
int speed;
public:
Car(int, string, int);
int getSpeed();
int getModel();
void accelerate();
void brake();
};
int Car::getSpeed()
{
return speed;
}
Car::Car(int year, string make, int speed = 0 )
{
}
void Car::accelerate()
{
speed +=5;
}
void Car::brake()
{
if( speed > 5 )
speed -=5;
else speed = 0 ;
}
int main ()
{
int year;
string make;
cout << "Please enter the model year of the car.\n";
cin >> year ;
cout << "Please enter the make of the car.\n";
cin >> make ;
Car myCar(year,make);
int i = 0;
for (; i<5; ++i)
{
myCar.accelerate();
cout << "Accelerating.\n" << "The current speed of the car is: " << myCar.getSpeed()<<endl;
}
{
int j = 0;
for (; j<5; ++j)
{
myCar.brake();
cout << "Decelerating.\n" << "The current speed of the car is: " << myCar.getSpeed()<<endl;
}
return (0);
}
}

This constructor
Car::Car(int year, string make, int speed = 0 )
{
}
initialize nothing. It has an empty body and neither initializer member list. Moreover according to the assignment the constructor has to have two parameters.
It can look the following way
Inside the class definition
inline Car( int year, std::string & make );
and the definition of the constructor itself
Car::Car( int year, const std::string make ) : year( year ), make( make ), speed( 0 )
{
}
The accessors can be declared like
int getYear() const;
int getSpeed() const;
const std::string & getModel() const;
^^^^^^^^^^^^^^^^^^^

The constructor
Car::Car(int year, string make, int speed = 0 )
{
}
is not doing what you describe. The three parameters (year, make, and speed) have the same names as Cars members, but are separate variables.
The result is that Cars members are default constructed, and the values passed by main() are effectively ignored.
To make things clearer, give the arguments different names, and initialise the members in an initialiser list.
Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}
It is permissible for the arguments to have the same names as class members, but this tends to be harder to read i.e. it is easier to misunderstand what the code is doing. In your case, you believe that giving the parameters the same name as class members serves to initialise the class members, and that is flat-out wrong. Either way, the constructor needs to explicitly initialise the members using the parameters, otherwise the class members receive default values (not the ones passed).
Also, if you want an argument with a default value, specify it in the definition of the class, not in the definition of the constructor. For example;
class Car
{
public:
Car(int, std::string, int = 0);
};
Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}
That makes things easier, particularly if the class definition is in a header file.

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include<stdio.h>
#include <cstdlib>
#include <string>
#include <iomanip>
double getaccelarate(double &, double &);
double getbrake(double &, double &);
double getcruise(double &, double &);
void outputStatusHeader();
void demo();
double updateDistanceTraveled(double &, double &);
int delta = 5;
//double brakee = 0;
double previousSpeed = 0;
double currentSpeed = 0;
using namespace std;
int main()
{
char command;
//The amount of elapsed time for each calculation interval
(fixed at 1 second)
const int timeInterval = 1;
//double currentSpeed=0;
//convert into the distance travelled by feet
int totalFeetTraveled = 0;
//the average speed travel
int averageSpeed = 0;
//double previousSpeed =0;
int averageSpeed_FeetPerSecond = 0;
int intervalFeetTraveled = 0;
int speed = 0;
//the amount of time that the time will increase by
//const int delta= 5;
while (true)
{
cout << "Command:";
cin >> command;
switch (command)
{
case 'a':
//double accelarate;
double speed;
speed = getaccelarate(currentSpeed, previousSpeed);
//cout << getaccelarate;
cout << "Accelerate"<<setw(20)<<"Accelerating"<<setw(5);
cout << speed;
double conve;
conve = updateDistanceTraveled(previousSpeed,
currentSpeed);
cout <<setw(10)<<setprecision(3)<<conve<<endl;
//updateDistanceTraveled(previousSpeed,currentSpeed);
break;
case 'b':
double brake;
brake = getbrake(previousSpeed, currentSpeed);
cout << "Brake" <<setw(20)<<"Braking"<<setw(5);
cout << brake;
//double brake1 = 0;
//brake1 = updateDistanceTraveled(previousSpeed,
currentSpeed);
cout << setw(10) << setprecision(3) << conve << endl;
break;
case 'c':
double cruise;
cruise = getcruise(previousSpeed, currentSpeed);
cout << "Cruise" << setw(20) << "Cruising" << setw(5);
cout << cruise;
cout << setw(10) << setprecision(3) << conve << endl;
break;
case 'h':
outputStatusHeader();
break;
case 'd':
demo();
break;
case 'q':
cout << " Exit program";
exit(1);
break;
default:
cout << "Invalid command" << endl;
break;
}
}
system("pause");
return 0;
}
//converting mph to feet perhours
double updateDistanceTraveled(double &previousSpeed,double &currentSpeed)
{
//getaccelarate(previousSpeed, currentSpeed);
double averageSpeed = 0;
double averageSpeed_FeetPerSecond = 0;
double intervalFeetTraveled=0;
//double totalFeetTraveled=0;
const int timeInterval = 1;
averageSpeed = (previousSpeed + currentSpeed) / 2;
averageSpeed_FeetPerSecond = averageSpeed * 5280.0 / 3600.0;
intervalFeetTraveled = averageSpeed_FeetPerSecond * timeInterval;
return intervalFeetTraveled;
/*totalFeetTraveled = totalFeetTraveled + intervalFeetTraveled;
return totalFeetTraveled;*/
}
//to decrease speed
double getbrake(double &previousSpeed, double &currentSpeed)
{
previousSpeed = currentSpeed;
currentSpeed -= delta;
return currentSpeed;
}
//to increase speed
double getaccelarate(double &previousSpeed, double &currentSpeed)
{
previousSpeed = currentSpeed;
currentSpeed = currentSpeed + delta;
return currentSpeed;
}
// to stay in current speed
double getcruise(double &previousSpeed, double &currentSpeed)
{
previousSpeed = currentSpeed;
return previousSpeed;
}
//unfinished demo
void demo()
{
cout << "Function Current State Current Speed Interval Distance
Total Feet (and miles) traveled" << endl;
cout << "-----------------------------------------------------------------------------------" << endl;
for (int x = 1; x < 4; x++)
{
double speed;
speed = getaccelarate(currentSpeed, previousSpeed);
//cout << getaccelarate;
cout << "Accelerate" << setw(20) << "Accelerating" << setw(5);
cout << speed;
double conve;
conve = updateDistanceTraveled(previousSpeed, currentSpeed);
cout << setw(10) << setprecision(3) << conve << endl;
}
}
//for supported commands
void outputStatusHeader()
{
cout << " supported commands\n"
<< " a accelerate\n"
<< " b brake\n"
<< " c cruise\n"
<< " d demo\n"
<< " h print this help text\n"
<< " q quit(end the program)"
<< endl;
}
{
cout << " supported commands\n"
<< " a accelerate\n"
<< " b brake\n"
<< " c cruise\n"
<< " d demo\n"
<< " h print this help text\n"
<< " q quit(end the program)"
<< endl;
}

Related

How to allow user input in objects and classes?

Consider the following code:
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber1, int quantity1, double cost1)
{
setItemNumber(itemNumber1);
setQuantity(quantity1);
setCost(cost1);
}
void setItemNumber(int itemNumber2)
{
itemNumber=itemNumber2;
}
bool setQuantity(int quantity2)
{
bool userTrue = true;
bool userFalse = false;
if (quantity2 < 0)
{
quantity = 0;
return userFalse;
}
else
{
quantity= quantity2;
return userTrue;
}
}
bool setCost(double cost2)
{
bool userTrue = true;
bool userFalse = false;
if (cost2 < 0.0)
{
cost = 0.0;
return userFalse;
}
else
{
cost= cost2;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
int total;
total = (quantity * cost);
return total;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
inventory secondObject(itemNumberInput1,quantityInput1,costInput1); // not sure if thats correct
cout << secondObject.setItemNumber(); // not working
cout << secondObject.setQuantity(); // not working
cout << secondObject.setCost(); // not working
return 0;
}
The code above is supposed to take three user inputs, and send them to the classes, and the classes will do their job.
I'm currently stuck at the end where its giving me an error.
In the second object where the values are asked from the user, it should send these values to the classes.
Instead, I'm getting the error.
How can I resolve this problem?
Here is the fixed code:-
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber, int quantity, double cost)
{
this->itemNumber = itemNumber;
this->quantity = quantity;
this->cost = cost;
}
void setItemNumber(int itemNumber)
{
this->itemNumber=itemNumber;
}
bool setQuantity(int quantity)
{
bool userTrue = true;
bool userFalse = false;
if (quantity < 0)
{
this->quantity = 0;
return userFalse;
}
else
{
this->quantity= quantity;
return userTrue;
}
}
bool setCost(double cost)
{
bool userTrue = true;
bool userFalse = false;
if (cost < 0.0)
{
this->cost = 0.0;
return userFalse;
}
else
{
this->cost= cost;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
return quantity * cost;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
// The below line is correct
// inventory secondObject(itemNumberInput1,quantityInput1,costInput1);
//Alternatively
inventory secondObject;
secondObject.setItemNumber(itemNumberInput1);
secondObject.setQuantity(quantityInput1);
secondObject.setCost(costInput1);
delete pointerA; // delete dynamically allocated memory to avoid memory leak
delete pointerB;
return 0;
}
Well you've constructed 'secondObject' object using the 3-arg constructor, using the user-entered values as parameters. Therefore, the member variables of this object are being set via the constructor and using the 'set' methods aren't really necessary. In your case, the set methods would be useful if you wanted to change the values later on. For example, lets pretend the user enters 10, 10, and 2.5 for the values. You're then using the constructor to construct the object with those values. The only difference is you're placing those values into variables first. But it works the same way. If you wanted to change the value of quantity later on, you could do secondObject.setQuantity(2); And the quantity for that object is now set to 2. The reason why your calls to .set aren't working is because you need to pass in parameters to these methods i.e. the value you want to set it to.
In regard to the destructor method being printed, objects are destroyed when they go out of scope so that the memory is released. Normally, nothing would happen in terms of output- the object would just go out of scope and the compiler would free up the memory and go about its' business. However, you've coded a custom destructor that prints out 'The Object is being destroyed', which it is at the end of the main. It's likely your constructor is working fine, I'm just not sure what you expect to be happening. I'd also suggest you read up on memory leaks in C++, especially in regard to the 'new' keyword.

Issues with retrieving information from a class module for output within a switch statement

I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.
Project Code section in question:
void materialsMenu()
{
Inventory record[MAX_REC];
int i, n;
cout << "\n=====Inventory Management=====\n";
cout << "\nHow many Materials are there to be used? : ";
cin >> n;
cout << "Enter " << n << " Materials\n";
for (i = 0; i < n; i++)
record[i].getdata();
cout << "\n\n---Material Information---\n";
cout << "\n" << setw(8) << "Item Name "
<< setw(10) << " Price per foot "
<< setw(19) << " Cost " << endl;
cout << endl << "-------------------------------------------" << endl;
for (i = 0; i < n; i++)
record[i].showdata();
}
void Inventory::getdata() {
cout << endl;
cout << "\nEnter Material Name : ";
cin >> itemName;
cout << "Enter Price Per Foot : ";
cin >> ppf;
cout << "Enter Total Length Needed in Feet (ft) : ";
cin >> length;
cout << endl;
m_cost = ppf*length;
m_costT=???????? **this is the issue**
}
Materials.H file contents:
#ifndef MATERIALS_H
using namespace std;
class Materials {
private:
char itemName[15];
float ppf;
float length;
double m_cost;
float m_costT;
public:
Materials()
{
ppf = 0;
length = 0;
m_cost = 0;
m_costT = 0;
}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
length = getLength();
ppf = getPpf();
m_cost = getCost();
m_costT = getTotal();
}
float getLength()
{
return length;
}
float getPpf()
{
return ppf;
}
double getCost()
{
return m_cost;
}
float getTotal()
{
return m_costT;
}
void getdata();
void showdata();
};
#endif // !MATERIALS_H
Consider something like this to hold your records. It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits. You are struggling to get that total because the Record class shouldn't care about this. The total is a concept outside of the scope of a Record. And as such, it is very difficult to calculate this from where you wanted to do it. (Though it is possible, it breaks all sorts of C++ rules and should be avoided)
Example:
class Record;
class RecordHolder
{
public:
int GetTotal()
{
int retVal = 0;
for(int i=0; i<10; i++) // Magic number 10 for demo purposes only...
{
retVal += records[i].m_cost; // Or use a public get function.
}
return retVal;
}
private:
Record records[10]; // Magic number 10 for demo purposes only...
};
The RecordHolder could also do printing, add/removing records, etc. It controls the records array. The Records are just Records and don't care about such management.

Why does my program output a huge decimal?

Okay so i created program that simulates a landscaping company and so we have to calculate the cost of Sod and fence. So when i enter in both the length and width they out put huge decimals for example
Parkton Landscaping
Enter Length: 10
Enter width: 12
Lanscaping Costs
Sod = 6871947680.00
Fence = 19327352760.00
Press any key to continue . . .
Sod is suppose to = 56.40
and Fence is suppose to = 990.00
please help here is my code and both files
#include <iostream>
#include <iomanip>
using namespace std;
#include "c:\Users\barta\OneDrive\Documents\Visual Studio 2015\Projects\Project 6\Project 6\Geometry.h"
#include "Pricing.h"
int main()
{
int length, width;
Pricing landscape;
Geometry geo;
const double Fenceprice = 22.50;
const double Sodprice = .47;
cout << "\t Parkton Landscaping " << endl;
cout << "Enter Length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
//Pricing(length, width);
//geo.getLength();
//geo.getWidth();
std::cout << std::fixed << std::setprecision(2);
landscape.displayOutput();
cout << "Sod = " << landscape.getsodCost(length) << endl;
cout << "Fence = " << landscape.getFenceCost(Fenceprice) << endl;
system("pause");
return 0;
}
here is the header file:
#pragma once
class Geometry
{//an object is how you access the class
public:// where the public function definitions are created
Geometry();// Default Constructor
Geometry(int, int);
Geometry(int);
void setLength(int); //assigns length
void setWidth(int); //assigns width
void setSide(int); //assigns side
//Constructor function that recieves the values for the rectangle
//Constructor function that recieves values for the cube
int getLength(),
getWidth(),
getSide(),
getArea(),
getPerimeter(),
getSurfaceArea();
private: //where the private members are created
int length,
width,
side;
void checkNum(int); //function that checks to see if the number is less than 0
};
Geometry::Geometry()
{
length = length;
width = width;
side = 0;
}
Geometry:: Geometry(int length, int width) /*function recieves 2 intergers and calls checkNum to validate if */
{
setLength(length);
setWidth(width);
checkNum(length);
checkNum(width);
}
Geometry:: Geometry(int sides)
{
checkNum(sides);
setSide(sides);
}
int Geometry::getLength()
{
return length;
}
int Geometry::getWidth()
{
return width;
}
int Geometry::getSide()
{
return side;
}
int Geometry::getArea()
{
return length * width;
}
int Geometry::getPerimeter()
{
return 2 * (length + width);
}
int Geometry::getSurfaceArea()
{
return 6 * (side * side);
}
void Geometry::setLength(int len)
{
length = len;
checkNum(len);
}
void Geometry::setWidth(int widths)
{
width = widths;
checkNum(widths);
}
void Geometry::setSide(int s)
{
side = s;
checkNum(s);
}
void Geometry::checkNum(int num) //function checks to see if the number is less than zero
{
if (num <= 0)
{
cout << "!!!!!!!!WARNING!!!!!! this isnt a number" << " program will now exit......" << endl;
system("pause");
exit(1);
}
}
Header file #2
#include "Geometry.h"
class Pricing : Geometry
{
public:
Pricing();
Pricing(int length, int width);
double getsodCost(double);
double getFenceCost(double);
void displayOutput();
private:
};
Pricing::Pricing(int length, int width) :Geometry(length, width)
{
}
Pricing::Pricing()
{
}
double Pricing::getsodCost(double price)
{
getArea();
return getArea()*price;
}
double Pricing::getFenceCost(double price)
{
getPerimeter();
return getPerimeter()*price;
}
void Pricing::displayOutput()
{
cout << "\n\n";
cout << "\t Lanscaping Costs " << endl;
}
Because you never initialize the objects with valid values, meaning Geometry::width and Geogrpapy::length are uninitialized and have indeterminate values. Using them uninitialized leads to undefined behavior.

First time working with classes in C++ : request for member of non class type

I've edited this after what you guys have told me. It gets all the way to this line and errors
cout << "The starting speed is " << honda.getSpeed() << endl << endl
[Error] request for member 'getSpeed' in 'honda', which is of non-class type 'Car(int, std::string, int) {aka Car(int, std::basic_string, int)}'
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Car {
private:
int yearModel;
string make;
int speed;
public:
Car(int carYearModel, string carMake, int carSpeed = 0) {
yearModel = carYearModel;
make = carMake;
speed = carSpeed;
}
void accelerate() {
speed += 5;
}
void brake() {
speed -= 5;
}
int getSpeed() {
return speed;
}
int getyearModel() {
return yearModel;
}
string getMake() {
return make;
}
};
int main() {
int count, YearModel, speed, make;
string carMake;
cout << "What is the speed?";
cin >> speed;
cout << "What is the year of the model?";
cin >> YearModel;
cout << "What is the make?";
cin >> make;
Car honda(int carYearModel, string carMake, int carSpeed);
cout << "The starting speed is " << honda.getSpeed() << endl << endl;
cout << "The year and model is " << honda.getyearModel() << endl << endl;
cout << "The make of the car is " << honda.getMake() << endl << endl;
return 0;
}
Car honda(int carYearModel, string carMake, int carSpeed);
declares a function named honda that takes three arguments are returns a Car. What you need is:
int carYearModel = 2015; // Some value
string carMake = "Honda"; // Makes sense to define honda
int carSpeed = 155; // Some value
// Create an object of type Car
Car honda(carYearModel, carMake, carSpeed);
Your getter methods should not be asking for user inputs.
Also, it should be Car honda(carYearModel, carMake, carSpeed); and you need to assign values to the variables carYearModel, carMake` and carSpeed before you can use them as method arguments. You can get these values from the user. You do not include the argument data types when calling the method. You only do that when defining the method.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Car {
private:
int yearModel;
string make;
int speed;
public:
Car(int carYearModel, string carMake, int carSpeed = 0) {
yearModel = carYearModel;
make = carMake;
speed = carSpeed;
}
void accelerate() {
speed += 5;
}
void brake() {
speed -= 5;
}
int getSpeed() {
return this.speed;
}
int getyearModel() {
return this.yearModel;
}
string getMake() {
return this.make;
}
};
int main() {
int count, carYearModel, carSpeed;
string carMake;
cout << "What is the speed?";
cin >> carSpeed;
cout << "What is the year of the model?";
cin >> carYearModel;
cout << "What is the make?";
cin >> carMake;
Car honda(carYearModel, carMake, carSpeed);
cout << "The starting speed is " << honda.getSpeed() << endl << endl;
cout << "The year and model is " << honda.getyearModel() << endl << endl;
cout << "The make of the car is " << honda.getMake() << endl << endl;
return 0;
}

C++ Class Variable Scope

I have a question about variable scope in a C++ class. The problem I'm working on says to create a class that holds an array of structures, with each structure holding the name, cost, and amount for a particular type of drink.
The class should have public member functions to buy a drink and display the menu, and private functions to get and validate money input (called by buy_drink) and to display an end of day report (called by the destructor).
I have a problem with the scope in the private function input_money. I get an error saying that the array has not been defined yet. I tested the display_data function (for printing the menu), and it worked fine on its own, but now I can't figure out why input_money would have a scope error and display_data wouldn't. Here is the header file:
/* need to create a class that holds an array of
5 structures, each structure holding string drink name,
double cost, and int number in machine
class needs public functions to display data and
buy drink
private functions input money -- called by buy_drink to accept,
validate, and return to buy drink the amount of money input
daily report -- destructor that reports how much money
was made daily and how many pops are left in machine */
#ifndef DRINKS_H
#define DRINKS_H
#include <string>
class Drinks
{
private:
struct Menu
{
std::string name;
double cost;
int number;
};
Menu list[5]; // array of 5 menu structures
double money_made; // track money made during the day
double input_money(int); // return validated money to buy_drink()
void daily_report(); // called by deconstructor
public:
Drinks();
~Drinks();
void display_data();
void buy_drink(int);
};
#endif
And here is the implementation file:
/* implementation file for Drinks class */
#include <iostream>
#include <string>
#include "drinks.h"
using namespace std;
const int SIZE = 5;
const int START_SIZE = 100;
Drinks::Drinks()
{
list[0].name = "Coke";
list[1].name = "Root Beer";
list[2].name = "Orange Soda";
list[3].name = "Grape Soda";
list[4].name = "Bottled Water";
for (int count = 0; count < (SIZE-1); count++)
list[count].cost = .75;
list[4].cost = 1;
for (int count = 0; count < SIZE; count++)
list[count].number = 20;
money_made = 0;
}
void Drinks::display_data()
{
for (int count = 0; count < SIZE; count++) {
if (count == 0)
cout << count+1 << list[count].name << "\t\t$ ";
else
cout << count+1 << list[count].name << "\t$ ";
cout << list[count].cost << "\t"
<< list[count].number << endl;
}
}
double input_money(int c)
{
double input;
cin >> input;
while (input != list[c].cost) {
if (input < list[c].cost) {
cout << "Not enough money.\n"
<< "Enter " << list[c].cost - input
<< " more cents to buy\n\n> ";
cin >> input;
}
else if (input > list[c].cost) {
cout << "Too much money.\n"
<< "I only need $" << list[c].cost << endl
<< "Enter " << input - list[c].cost
<< " less money: ";
cin >> input;
}
}
return input;
}
void Drinks::buy_drink(int c) // this receives an int choice (to access corresponding structure in the list array)
{
double input;
cout << "Enter " <<list[c].cost
<< " to purchase " << list[c].name
<< "\n\n> ";
input = input_money(c); // input money returns a validated and accurate price for the drink and is passed the choice to access array
list[c].number -= 1;
money_made += list[c].cost; // add cost of drink to money made
}
void Drinks::daily_report()
{
int end_size = 0;
for (int count = 0; count < SIZE; count++)
end_size += list[count].number;
cout << "Today, you made $" << money_made << endl;
cout << "There are " << START_SIZE - end_size
<< " drinks left in the machine" << endl;
}
Drinks::~Drinks()
{
daily_report();
cout << "goodbye mr anderson\n";
}
Any help would be much appreciated! I can't seem to figure out why the input_money function does not have access to the structures in the array.
Thank you!
EDIT: Total noob mistake/carelessness. Forgot to add the name of the class in the input_money function definition and use the scope resolution operator (i.e. should be Drinks::input_money(int c)). Thanks to those who answered.
double Drinks::input_money(int c)
// ^^^^^^^^ forgot this
You forgot the class name while providing the implementation.
Notice the difference between your definition of
void Drinks::display_data
and
double input_money(int c)
In the second case you have defined a free function that is not a member of the class and has no information about the class members. It should be
double Drinks::input_money(int c)