Creating shopping cart - c++

for my class were creating a mini store, and I have the three main functions that work, main.cpp, items.cpp, items.h. but the shoppingcart.cpp and the shoppinfcart.h keeps giving me issues, because I'm trying to pass the parameters from main.cpp, for example (sc1.add(&a) to the functions in shoppingcart.h and shopping cart.cpp.
I have attached copy of my code. any help will be appreciated.
Item.h
#ifndef Items_hpp
#define Items_hpp
#include <string>
#include <iostream>
using namespace std;
class Items {
private:
string ItemName;
float ItemPrice;
int ItemQuant;
public:
Items();
Items(string in, float ip, int iq);
void Name(string in);
string entername();
void CalcPrice( float ip);
float enterprice();
void CalcQuant(int iq);
int enterquant();
};
#endif
Items.cpp
#include "Items.h"
Items::Items()
:ItemName("")
,ItemPrice(0)
,ItemQuant(0)
{
}
Items::Items(string in, float ip, int iq)
:ItemName(in)
,ItemPrice(ip)
,ItemQuant(iq)
{
}
void Items:: CalcPrice(float ip)
{
ItemPrice = ip;
}
void Items::CalcQuant(int iq)
{
ItemQuant = iq;
}
void Items:: Name(std::string in)
{
ItemName = in;
}
float Items:: enterprice()
{
return ItemPrice;
}
int Items:: enterquant()
{
return ItemQuant;
}
string Items:: entername()
{
return ItemName;
}
a snippet of the code for adding items to vector
ShoppingCart.cpp
#include "ShoppingCart.h"
#include <vector>
void ShoppingCart ::add(&its)
{
shopitems.push_back(&its);
}
ShoppingCart.h
#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp
#include <iostream>
#include <string>
#include <vector>
#include "Items.h"
using namespace std;
class ShoppingCart
{
private:
vector <const char its> shopitems;
string cname; //customers name
string cdate; // todays date
public:
ShoppingCart();
ShoppingCart(string cname);
void add( char *its);
};
#endif
an example of main
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Items.h"
#include "ShoppingCart.h"
using namespace std;
int main() {
char choice;
int itemsbuy;
float org = .75;
float appl = .25;
float pear = 1.00;
float bana = .85;
float grape = 6.00;
float oatmlk = 5.00;
float almmlk = 6.00;
float cashmlk= 5.00;
float soymlk = 4.00;
float cocomlk = 3.00;
float twopermlk = 3.00;
float vitdmlk = 4.00;
float fatmlk = 4.00;
float goatmlk = 6.00;
float rasinbran = 4.00;
float granola = 5.00;
float honeybunches = 6.00;
float twix = 4.00;
float honey = 5.00;
float yogurt = 1.50;
float cashyog = 2.00;
float eggs = 1.80;
float vegeggs = 3.00;
float cheese = 2.00;
float alcheese = 3.00;
int itemop;
int itemno;
int productcounter = 0;
int productsum= 0;//might need.
cout << "Welcome to J&S Breakfast Grocery store!"<<endl;
cout << "--------------------------------------"<<endl;
cout << "How many items will you be purchasing today?"<<endl;
cout << endl;
cin >> itemsbuy;
ShoppingCart sc1; //**intializing "shoppingcart.h"**//
for (int i = 0; i < itemsbuy; i++) {
cout << "Menu:"<<endl;
cout << "---------------------------"<<endl;
cout << "A. Fruits"<<endl;
cout << "B. Non-Diary"<<endl;
cout << "C. Diary" <<endl;
cout << "D. Cereal" <<endl;
cout << "E. Other"<<endl;
cout << "Please select your type of items to add to cart"<<endl;
cin >> choice;
cout << endl;
switch (choice) {
case 'A':
case 'a':
cout << "Menu:" <<endl;
cout << "---------------------------"<<endl;
cout << "1.Oranges -$ "<< org<<endl;
cout << "2.Apples -$ "<< appl << endl;
cout << "3.Pears - $"<<pear<<endl;
cout << "4.Bananas - $" << bana << endl;
cout << "5.Grapes - $" << grape << endl;
cout << endl;
cout << "Chooose option"<<endl;
cin >> itemop;
cout << "How Many?"<<endl;
cin >> itemno;
if (itemno > itemsbuy) {
cout << "Error, cannot add more than youre planning to buy. Please start over."<<endl;
break;
}
else {
if (itemop ==1) {
Items a("Oranges" , org, itemno);
productcounter++;
sc1.add(&a); //**trying to pass parameter here**//
if (productcounter == itemsbuy) {
cout<< "Error. You are attempting to buy more than you planned. Please Start over. Thank you."<<endl;
}
}

There are a few mistakes in your code.
ShoppingCart.h:
vector <const char its> shopitems;.
std::vector is declared in the following syntax:
std::vector<data type> variable name.
It looks like that you're trying to create a container of Items and store them. Therefore instead of vector<const char> shopitems, you should use:
vector<Items> shopitems instead.
also:
void add(char* its); is incorrect, since this method will be adding Items to your shopitems vector. Change it to: void add(const Items& its);
This will pass a const reference of object Items, meaning the method will not copy the entire class Items when it is called, and the object will not be modifiable.
ShoppingCart.cpp:
Let's also fix the syntax and semantic in your .cpp file, the correct now is:
void ShoppingCart::add(const Item& its)
{
shopitems.push_back(its); //& is not necessary here.
}
Main.cpp
Now, in your main file let's call the method correctly. sc1.add(&a);, the: & here is telling it to pass the memory address of where the object Items a is located. Let's correct this, and pass the object Items a normally, simply write: sc1.add(a);
Logic error
There is one final logic error I caught in your code, that is: if (productcounter == itemsbuy). If itemsbuy (The amount of items you want to buy today) is: 1. Then, productcounter is also 1 and you can't buy anything, this should be: if (productcounter > itemsbuy)

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.

I clearly initialized my class, but I am getting errors saying I didn't [duplicate]

This question already has answers here:
Method for solving error: "cannot instantiate abstract class"
(3 answers)
Closed 6 years ago.
error1-error C2259: 'HourlyEmployee' : cannot instantiate abstract class
error2-object of abstract class type "HourlyEmployee" is not allowed:
pure virtual function "Employee::printPay" has no overrider
This error is in this part and I don't understand the problem.
VE.push_back(new HourlyEmployee(empID, hours, payRate));
main.cpp:
#include "hourly.h"
#include "lab7.h"
#include "salarie.h"
#include <iostream>
#include <iomanip>
#include <vector>
void getInput(vector <Employee *> & VE);
void printList(const vector <Employee *> & VE);
using namespace std;
int main()
{
vector <Employee *> VEmp;
getInput(VEmp);
printList(VEmp);
cout << "Lab 7 completed by: " << "youssef zaki " << endl;
system("pause");
return 0;
}
void getInput(vector<Employee*>& VE)
{
std::vector < HourlyEmployee > ;
int empID,
choice;
double salary,
hours,
payRate;
do
{
cout << "Enter 1 for Hourly Employee" << endl;
cout << "Enter 2 for Salaried Employee" << endl;
cout << "Enter 3 to stop: ";
cin >> choice;
cout << endl;
// process option
switch (choice)
{
case 1:
cout << "Enter the ID: ";
cin >> empID;
cout << "Enter the number of hours worked: ";
cin >> hours;
cout << "Enter the pay rate: ";
cin >> payRate;
VE.push_back(new HourlyEmployee(empID, hours, payRate));
break;
case 2:
cout << "Enter the ID: ";
cin >> empID;
cout << "Enter the salary: ";
cin >> salary;
VE.push_back(new SalariedEmployee(empID, salary));
break;
case 3:
break;
default:
cout << "Error: invalid option" << endl;
}
cout << endl;
} while (choice != 3);
}
void printList(const vector<Employee*>& VE )
{
for (std::size_t i = 0; i != VE.size(); ++i)
{
VE[i]->printPay();
}
}
employ.h file:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
class Employee
{
private:
int EmpID;
public:
Employee(int);
~Employee();
int getEmpID() const;
virtual void printPay()=0;
};
#endif
employ.cpp:
#include "lab7.h"
#include <iostream>
#include <iomanip>
#include <vector>
Employee::Employee(int empID)
{
EmpID = empID;
}
Employee::~Employee()
{
}
int Employee::getEmpID() const
{
return EmpID;
}
employsalarie.h file:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
class SalariedEmployee: public Employee
{
private:
double salary;
public:
SalariedEmployee(int, double);
~SalariedEmployee();
double getSalary() const;
void printPay();
};
#endif
employsalry.cpp:
#include "salarie.h"
#include <vector>
SalariedEmployee::SalariedEmployee(int empID, double salary) : ` ` Employee(empID)
{
salary = salary;
}
SalariedEmployee::~SalariedEmployee()
{
}
double SalariedEmployee::getSalary() const
{
return salary;
}
void SalariedEmployee::printPay()
{
double weeklyPay = salary / 52;
cout << fixed << showpoint << setprecision(2);
cout << "The pay for the salaried employee with ID number ";
cout << getEmpID() << " is $" << weeklyPay << endl;
}
hourlyemploy.h:
#ifndef HOURLYEMPLOYEE_H
#define HOURLYEMPLOYEE_H
#include "lab7.h"
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
class HourlyEmployee : public Employee
{
private:
double hours;
double payRate;
public:
HourlyEmployee(int, double, double);
~HourlyEmployee();
double getHours() const;
double getPayRate() const;
void printPay(double);
};
#endif
hourlyemploy.cpp:
#include "hourly.h"
#include <iostream>
#include <iomanip>
#include <vector>
HourlyEmployee::HourlyEmployee(int empID, double hours, double payRate)
: Employee(empID)
{
this->hours = hours;
this->payRate = payRate;
}
HourlyEmployee::~HourlyEmployee()
{
}
double HourlyEmployee::getHours() const
{
return hours;
}
double HourlyEmployee::getPayRate() const
{
return payRate;
}
void HourlyEmployee::printPay(double)
{
double weeklyPay = hours * payRate;
cout << fixed << showpoint << setprecision(2);
cout << "The pay for the hourly employee with ID number ";
cout << getEmpID() << " is $" << weeklyPay << endl;
}
Error message gives you all the information:
error1-error C2259: 'HourlyEmployee' : cannot instantiate abstract class error2-object of abstract class type "HourlyEmployee" is not allowed:
pure virtual function "Employee::printPay" has no overrider
In HourlyEmployee class you have not overriden void printPay(), you only added method of the same name but different argument list: void printPay(double);.
I suggest to use override keyword when overriding virtual methods:
void printPay(double) override; // this will generate error (signature mismatch)
while:
void printPay() override; // will work just fine
Another problem from your code:
SalariedEmployee::SalariedEmployee(int empID, double salary) : ` ` Employee(empID)
{
salary = salary;
}
here salary is a local variable in SalariedEmployee, to properly initialize class variable use
this->salary = salary;
More hints to earn extra points (From your HW) :-)
Do not use using namespace std;
Do not use endl, but instead "\n"
Do not use raw pointers, use std::unique_ptr<> and if you need to share it then std::shared_ptr<>. Those two together with std::make_unique and std::make_shared.
In you code you use new but I never found delete - thats asking for memory leaks.

Printing different strings for reading different object variables

I wish to output different string for reading variables. For example, below, I wish to print Enter english marks before reading english marks using eng.setmarks(). Please suggest a way to implement this.
Here is my code: (look at for loop below)
#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
class student {
char name[20];
int age;
class marks {
int marks;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
};
public:
marks eng, math, phy, chem, cs; // nested objects are public
void setname( char* n) {
strncpy( name, n, 20);
}
char* getname() {
return name;
}
void setage( int a) {
age = a;
}
float total() {
size_t total = eng.getmarks() + math.getmarks() +
phy.getmarks() + chem.getmarks() + cs.getmarks();
return total/500.0;
}
};
int main() {a
student new_stud;
char temp[20];
cout << "Enter name: ";
cin >> temp;
cin.get( temp, sizeof(temp));
new_stud.setname(temp);
int age;
cout << "Enter age: ";
cin >> age;
new_stud.setage( age);
for( size_t i = 0; i < 5; ++i) {
// I wish to output: "Enter marks in" + subject_name, but harcoding it seems tedious
}
cout << "\nTotal Percentage: " << new_stud.total();
return 0;
}
So if I understand correctly, you would like to print out the name of the variable which you are about to read into. Now this can't be done on the way you want it. The best thing you can do is make an array of subject names, and an array of marks.
string[5] Subjects = {"Maths", "English", "Chemistry", "Physiscs", "Computer Sciences"};
marks[5] Marks;
for(int i=0;i<5;i++) {
cout << "Please enter marks in " << Subjects[i] << ":" << endl;
int a;
cin >> a;
Marks[i].setmarks(a);
}
You could also make the marks class have a field subject name, and give it a function inputfromuser(), like this:
class marks {
int marks;
string subjectName;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
void inputfromuser() {
cout << "Please enter marks in " << subjectName << ":" << endl;
cin >> marks;
}
};
Sorry for me using the std::string type, I am not very comfortable with the raw char[] way to handle texts.

Execution time comparison [duplicate]

This question already has answers here:
How to Calculate Execution Time of a Code Snippet in C++
(18 answers)
Closed 8 years ago.
I have a snowball launcher game codes. There is a arm to launch snowball and the target in the game. I have 2 different block of codes that makes the calculation for releasing angle of the arm with the input of length of the arm and target's x and y coordinates. One of them is:
#include <iostream>
#include <cmath> // math library
#include <windows.h> // system()
using namespace std;
class SnowballMachine{
private:
double L,X,Y, theta; //L for Lenght of the arm, X and Y is the coordinates
const double pi = 3.14159265; //Theta=Release angle
public:
void input() //get inputs for lenght of the arm and coordinates
{
cout<<"Please enter the coordinations of the target(for Target(x,y) enter 40 28)" <<endl;
cin>>X>>Y;
cout<<"Please enter the length of the arm: "<<endl;
cin>>L;
}
double calculate(){ //calculates the release angle with perpendicular slope comparison
if(L*Y <= X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))
{
theta=asin((L*Y + X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y, 2.0)+pow(X, 2.0)));
return theta;
}
else
{
theta=asin((L*Y - X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y,2.0)+pow(X, 2.0)));
return theta;
}
}
void ThetaDisplay() //displays output
{
cout << "The releasing angle is "<<180-(theta*180/pi)<<" degrees"<<endl;
}
};
//const values for options to get input
const int OPEN_GATE=1 ;
const int LOAD_SNOWBALL = 2;
const int ADJUST_ARM=3;
const int RELEASE_ARM=4;
const int QUIT=5;
int menu(); // get a command
void execute(int, SnowballMachine &Dummy); // run a given command
int main()
{
SnowballMachine A; //calling the class
A.input(); //calling the functions
A.calculate();
int choice;
A.ThetaDisplay();
do //select the options
{
choice = menu();
execute(choice, A);
} while (choice != QUIT );*/
return 0;
}
int select;
system("cls");
do
{
cout <<"1....Open the gate\n";
cout <<"2....Load the Snowball\n";
cout <<"3...Adjust the arm\n";
cout <<"4....Release the Snowball\n";
cout<<"5...Quit\n";
cout <<"enter selection: ";
cin >> select;
} while (select!=1 && select!=2 && select!=3 && select!=4 &&select!=5);
return select;
}
void execute(int cmd, SnowballMachine &Dummy)
{
//options switch method
switch (cmd)
{
case OPEN_GATE: cout << "Opening the gate\n";
break;
case LOAD_SNOWBALL: cout << "Loading the snowball\n";
break;
case ADJUST_ARM:cout<<"Adjusting the arm\n";
break;
case RELEASE_ARM:cout<<"Releasing the arm\n";
Dummy.calculate();
Dummy.ThetaDisplay();
break;
case QUIT:cout<<"Quitting!!!";
break;
default:
cout <<" Invalid Entry. Try it again please.";
}
This is the first one. Second one is:
This is the main.cpp
#include <iostream>
#include "Snowball.h"
using namespace std;
int main()
{
Snowball A;
A.Display();
A.ArmLength();
A.Input();
A.SetStartPOS();
for(double i = A.getLength(); i>A.getStartPOS(); i-=A.DELTAX)
{
if (A.Derivative(A, i)*.9999 >= ((A.getY()-A.foo(i))/(A.getX()-i))*1.0001)
{
A.setxPointcirc(i);
break;
}
}
A.AngleDisplay();
return 0;
}
This is the part of main.cpp which is snowball.cpp which calls all the functions:
#include "Snowball.h"
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void Snowball::Input()
{
cout << "Enter the x-postion of the target: ";
cin >> x;
while(x < armlength || x < armlength*-1)
{
cout << endl;
cout << "Please make sure your x is greater than " << armlength << '.' << endl;
cout << "Enter the x-postion of the target. ";
cin >> x;
}
cout << "Enter the y-postion of the target: ";
cin >> y;
while(y < 0 || (y < armlength && x<armlength) )
{
cout << endl;
cout << "Enter the y-postion of the target: ";
cin >> y;
}
this->x =x;
this->y =y;
}
void Snowball::ArmLength()
{
cout << "Enter the Length of the Arm: ";
cin >> armlength;
this->armlength =armlength;
}
void Snowball::Display()
{
cout << "Welcome to the Snowball Launcher. \n\n";
}
double Snowball::foo(double x)
{
double z;
z = sqrt(powf(armlength, 2.0)-powf(x, 2.0));
return z;
}
double Snowball::Derivative(Snowball &foo_dummy, double x)
{
return (foo_dummy.foo(x+DELTAX/2.0) - foo_dummy.foo(x-DELTAX/2))/DELTAX;
}
void Snowball::AngleDisplay()
{
theta = rad2deg(acos(xPointCircle/armlength));
cout << "\nTarget Destroyed.\nAngle Required is: " << theta << " degrees." << setprecision(4) <<endl;
}
void Snowball::SetStartPOS()
{
StartPOS = armlength*-1;
}
void Snowball::setxPointcirc(double i)
{
xPointCircle = i;
}
And here is the getters and setters with declaring the const and variables header:
#ifndef SNOWBALL_H_INCLUDED
#define SNOWBALL_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
class Snowball {
private:
double rad2deg(double h) {return h*(180/pi); };
double x, y, theta, xPointCircle, StartPOS, armlength;
public:
static const double pi = 3.1415926535897;
static const double DELTAX = 0.001;
double foo(double x);
double Derivative(Snowball &foo_dummy, double x);
void Display();
void Input();
double getLength() {return armlength; }
double getStartPOS() {return StartPOS; }
double getY() {return y; }
double getX() {return x; }
void setxPointcirc(double i);
void ArmLength();
void AngleDisplay();
void SetStartPOS();
};
#endif
Here is my question: I get the same results with both 2 different block of codes. I want to
test which execution time is less(which one would be faster?).
Generally the way this is approached is to call the function n number of times (for large n) and calculate the time taken across the calls.
For instance, call it "the first way" 100000 times (getting the time before and time after) then calculate it "the second way" the same number of times (again checking the time before and after). By subtracting the two, you'll get a decent estimate of which is faster/slower.
Note that you need to test it many numbers of times to get an accurate result, not just once!

msvr100.dll free (void * pblock)

Hello there stackOverflow.
I am a noob when it comes to c++ and today i tried to compile my first program including classes. This ofcourse gave me an error and i don't really know what i did wrong since its my first time compling a class program :P
i tried to google it and it said something about either the DLL.'s are building wrong? (i got it all in debug mode, so it can't be that). So the other option is: i might be freeing the memory wrongly or something like that, can anyone explain where i did wrong?
i tried to compare the code to the tutorial i found. But that didn't help. (the tutorial im referring to is: http://www.youtube.com/watch?v=vz1O9nRyZaY ). The error i'm getting is
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0)
{
errno = _get_errno_from_oserr(GetLastError());
}
}
and my source code / header files are:
main.cpp
#include <iostream>
#include <string>
#include "conio.h"
#include <crtdbg.h>
#include "Tax.h"
using namespace std;
int main()
{
string name;
double tax;
double income;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your annually income: ";
cin >> income;
cout << "Enter your tax rate in pure numbers: ";
cin >> tax;
Tax Customer_1(name, income, tax);
cout << endl << "Customer name: " << Customer_1.getName() << endl <<
"Income annually: " << Customer_1.getIncome() << endl <<
"Tax percent(in real numbers): " << Customer_1.getTax() << endl <<
"Your income after tax, per month is: " << Customer_1.calculateTax() << endl;
cout << endl;
_getch();
return 0;
}
Tax.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef TAX_H
#define TAX_H
class Tax
{
public:
//Default constructor
Tax();
//Overload constructor
Tax(string, double, double);
//destructor
~Tax();
//Accessor functions
string getName() const;
double getIncome() const;
double getTax() const;
//Mutator functions
void setName(string);
void setIncome(double);
void setTax(double);
double calculateTax() const;
private:
//Member variables
string newName;
double newIncome;
double newTax;
};
#endif
Tax.cpp
#include "Tax.h"
Tax::Tax()
{
newIncome = 0.0;
newTax = 0.0;
}
Tax::Tax(string name, double income, double tax)
{
newName = name;
newIncome = income;
newTax = tax;
}
Tax::~Tax()
{
}
string Tax::getName() const
{
return newName;
}
double Tax::getIncome() const
{
return newIncome;
}
double Tax::getTax() const
{
return newTax;
}
void Tax::setName(string name)
{
newName = name;
}
void Tax::setIncome(double income)
{
newIncome = income;
}
void Tax::setTax(double tax)
{
newTax = tax;
}
double Tax::calculateTax() const
{
return (( newIncome - ( newIncome * (newTax / 100))) / 12); // ((68400 - ( 68400 * (38/100 = 0.38))) / 12)
}
I've (slightly) modified your code to work out, try this:
tax.h:
#include <iostream>
#include <string>
#ifndef TAX_H
#define TAX_H
class Tax
{
public:
//Default constructor
Tax();
//Overload constructor
Tax(std::string, double, double);
//destructor
~Tax();
//Accessor functions
std::string getName() const;
double getIncome() const;
double getTax() const;
//Mutator functions
void setName(std::string);
void setIncome(double);
void setTax(double);
double calculateTax() const;
private:
//Member variables
std::string newName;
double newIncome;
double newTax;
};
#endif
tax.cpp:
#include "tax.h"
Tax::Tax()
{
newIncome = 0.0;
newTax = 0.0;
}
Tax::Tax(std::string name, double income, double tax)
{
newName = name;
newIncome = income;
newTax = tax;
}
Tax::~Tax() {}
std::string Tax::getName() const
{
return newName;
}
double Tax::getIncome() const
{
return newIncome;
}
double Tax::getTax() const
{
return newTax;
}
void Tax::setName(std::string name)
{
newName = name;
}
void Tax::setIncome(double income)
{
newIncome = income;
}
void Tax::setTax(double tax)
{
newTax = tax;
}
double Tax::calculateTax() const
{
return (( newIncome - ( newIncome * (newTax / 100))) / 12);
}
main.cpp
#include "tax.h" // <iostream> and <string> are here
// never put 'using namespace std' in a header file
using namespace std;
int main()
{
string name;
double tax;
double income;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your annually income: ";
cin >> income;
cout << "Enter your tax rate in pure numbers: ";
cin >> tax;
Tax Customer_1(name, income, tax);
cout << endl << "Customer name: " << Customer_1.getName() << endl <<
"Income annually: " << Customer_1.getIncome() << endl <<
"Tax percent(in real numbers): " << Customer_1.getTax() << endl <<
"Your income after tax, per month is: " << Customer_1.calculateTax() << endl;
cout << endl;
return 0;
}
Take note of what has been replaced and the headers you were using; judging by the _getch() at the end of the code, I'm assuming you were using that so that your console window would not go away while debugging; if that was the case, you could instead do something with cin and the strings you already have like so:
...
cin.clear(); // clear buffer for erroneous 'enter' presses
cin >> name; // console will pause until you press enter
return 0;
Though if your intention was to actually have the console pause (vs. the program just ending), you might want to consider other (more elegant) solutions but that is beyond the scope of this question.
A couple of notes: the reason your program worked when not in debug mode (i.e. you went to 'release') is your inclusion of the <crtdbg.h> header; this file is only valid in a debug configuration and you really shouldn't include it if your not using anything in it (which you're not in your code). I also took out the using namespace std; in your tax.h file as there are numerous reasons not to include using namespace std in a header.
I hope that can help