C++ class using a variable from private class - c++

I am trying to use a variable from the private class and both add and subtract from it at different times, first add 5 to it 5 times then subtract 5 from it 5 times and each time i have to display its value. Currently i have:
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class car {
private:
int year;
string make;
int speed;
public:
void StoreInfo(int y, string m, int s);
int getSpeed() { return speed; }
int accelerate() { speed += 5; }
int brake() { speed -= 5; }
};
void car::StoreInfo(int y, string m, int s) {
year = y;
make = m;
speed = s;
}
car fillFields() {
car Filler;
int year; // Local variables to hold user input
string make;
int speed = 0;
// Get the data from the user
cout << "Enter year: ";
cin >> year;
cout << "Enter make: ";
cin.get(); // Move past the '\n' left in the
// input buffer by the last input
getline(cin, make);
cout << "The current speed is " << speed << endl;
Filler.StoreInfo(year, make, speed);
return Filler;
}
int main() {
car numbers = fillFields();
car::accelerate();
return 0;
}
This code accepts the input but does not work after that i realize that the car::accelerate() line in the main is incorrect now but how would i use it correctly?

First accelerate and brake do not return any value so you can make them void
void accelerate() { speed += 5; }
void brake() { speed -= 5; }
accelerate is non-static member function and needs an object so you need to call it like:
numbers.accelerate();
And for example change your main function like this to accerelate once and then brake and see the speed:
int main() {
car numbers = fillFields();
numbers.accelerate(); // +5
cout << "The current speed is " << numbers.getSpeed() << endl;
numbers.brake(); // -5
cout << "The current speed is " << numbers.getSpeed() << endl;
return 0;
}
Outputs:
Enter year: Enter make: The current speed is 0
The current speed is 5
The current speed is 0
Demo
You can replace car::StoreInfo with a constructor, because it does what the constructors are meant for. And don't forget to initialize your variables.

numbers.accelerate();
You are not using any static data. You could rename numbers variable if you want.

Related

Why is my program giving weird results?

The following snippets are the header file and the actual main() function. I am using Visual Studio 2017 with Windows 10.
.h
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
using namespace std;
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
#endif
.cpp
#include <iostream>
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data item1;
cout << "Enter rate and amount" << endl;
cin >> item1.rate >> item1.amount;
cout << item1.price << endl;
cin.get();
cin.get();
return 0;
}
It keeps showing this as the output: "687194768".
I also tried initializing the variables but it does not seem to work.
What you probably want is:
struct Sales_data
{
int amount = 0;
int rate = 0;
int price() const { return amount * rate; }
};
And then
std::in >> item1.rate >> item1.amount;
std::cout << item1.price() << std::endl;
Price here is being calculated only at initialisation time to get its initial value, however since amount and rate have not been initialised yet, the result is undefined.
It is not a function.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
You most likely wanted a function, e.g.:
struct Sales_data
{
int amount;
int rate;
int calcPrice()
{
return = amount * rate;
}
};
std::cout << item1.calcPrice() << std::endl;
Or you would have to refactor to initialise amount and rate to make use of such syntax, e.g. with a constructor.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
Sales_data(int amount, int rate) : amount(amount), rate(rate) {}
};
Sales_data x(10, 5);
//x.price == 50
the reason the code is printing that is because you are calculating that price with uninitialized variables...
define a function in the struct and call it after the input is given
void calculatePrice() {
price = amount * rate;
}
cin >> item1.rate >> item1.amount;
item1.calculatePrice();
cout << item1.price << endl;
As others have commented, your definition for Sales_data uses amount or rate before they were ever initialised. This is undefined behaviour, and your compiler is more or less free to do whatever it pleases with this.
Many compilers will initialise variables with some sort of recognisable guard value (a popular choice is 0xDEADBEEF) as a way to make it quite obvious when a value is uninitialised when looking at it with a debugger. In this case, it looks like your compiler uses 0xCCCCCCCC as that guard value:
(lldb) p (int) 0xcccccccc * (int) 0xcccccccc
(int) $2 = 687194768

How to read the value and output the value in C++

first of all am very new to C++. I am having some problem with my code. The program should able to get/read the value user entered and output it back. I tried get/set C++ methods, but am having some problem with getting and outputting the value in my main. The following is my code,
#include <iostream>
using namespace std;
class Store {
public:
//get and Set Price
void setPrice(int x){
price = x;
}
int getPrice(){
return price;
}
//Get and set % Marked Up
void setPercentageMarkedUp(int y){
markedUpPrice = y;
}
int getPercentageMarkedUp(){
return markedUpPrice;
}
//Get and set percentage Sales tax
void setPercentageSalesTax(int y){
percSalesTax = y;
}
int getPercentageSalesTax(){
return percSalesTax;
}
private:
int price;
int markedUpPrice;
int percSalesTax;
};
int main(){
int price;
Store obj;
cout << "enter the Original Price of the item: "<<endl;
obj.getPrice();
cout<<"the value is:"<<price<<endl;
return 0;
}
As am very new to both C++ and StackOverflow, please dont downgrade me for asking this simple question. I know its very basic. Will definitely appreciate those who helps. Thanks in advance.
Just need to update the main as follows
int main(){
Store obj;
int n_price;
cout << " Enter Original Price: " << endl;
cin >> n_price;
obj.setPrice(n_price);
cout << "Original Price: " << n_price<< endl;
return 0;
}
Thanks everyone. :)

C++ object oriented problems [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is an assignment i am trying to figure out:
Create a new project named Project3 and create a class named Rover
Within the Rover class, specify the following member instance variables:
name(string)
x position on a grid (integer)
y position on a grid (integer)
direction by compass – N, S, E, or W (String)
speed (0 – 5 meters per second, integer)
Within the Rover class, specify the following methods:
Default constructor – set the rover’s position to (0,0), its speed to 0, its direction to
North.
Constructor that receives parameters to initialize all five instance variables described above
Setter methods for each instance variable
Getter methods for each instance variable
getRoverData – returns a string that displays values for each instance variable of the
current rover object, placing each value on a separate line, as follows:
Rover name: A
X-position: 0
Y-position: 0
Direction: E
Speed: 1
Create a class client (main) that creates an array of the a maximum of five rovers and gets the initial
values for all rovers from the user. After the user specifies values for each rover, display a summary
of the rover’s values as shown above.
I have about a billion errors and i dont know why.
using namespace std;
class Rover {
private:
string name;
int x;
int y;
string direction;
int speed;
int position[10][10];
public:
void Rover();
void constructor(string name, int x, int y, string direction, int speed);
void setName(string name);
void setX(int x);
void setY(int y);
void setDirection(string direction);
void setSpeed();
string getName();
int getX();
int getY();
string getDirection();
int getSpeed();
string getRoverData();
};
void Rover::Rover() {
r1.position[0][0];
r1.speed = 0;
r1.direction = "N";
}
string Rover::getRoverData() {
cout << "Rover name: " << r1.getName() << endl;
cout << "X-position: " << r1.getX() << endl;
cout << "Y-position: " << r1.getY() << endl;
cout << "Direction: " << r1.getDirection() << endl;
cout << "Speed: " << r1.getSpeed() << endl;
}
void Rover::constructor(string name1, int x1, int y1, string direction1, int speed1) {
r1.name = name1;
r1.x = x1;
r1.y = y1;
r1.direction = direction1;
r1.speed = speed1;
}
void Rover::setName(string name) {
r1.name = name;
}
void Rover::setX(int x) {
r1.x = x;
}
void Rover::setY(int y) {
r1.y = y;
}
void Rover::setDirection(string direction) {
r1.direction = direction;
}
void Rover::setSpeed(int speed) {
r1.speed = speed;
}
string Rover::getName() {
return name;
}
int Rover::getX() {
return x;
}
int Rover::getY() {
return y;
}
string Rover::getDirection() {
return direction;
}
int Rover::getSpeed() {
return speed;
}
int main(int argc, char** argv) {
string name;
int x;
int y;
string direction;
int speed;
Rover r1;
r1.constructor("Yoda", 3, 3, "N", 3);
cout << "Enter name for Rover: ";
cin >> name;
r1.setName(name);
cout << "Enter its x position: ";
cin >> x;
r1.setX(x);
cout << "Enter its y position: ";
cin >> y;
r1.setY(y);
cout << "Enter direction N,E,S,W: ";
cin >> direction;
r1.setDirection(direction);
cout << "Enter its speed: ";
cin >> speed;
r1.setSpeed(speed);
r1.getRoverData();
return 0;
}
Your example appears incomplete. I'm guessing you just missed including the following lines in your post
#include <string>
#include <iostream>
using namespace std;
First, constructors do not have a return type so void Rover(); makes no sense. Remove void and you're golden there.
Second, what exactly do you think r1 is supposed to be? The compiler should tell you the identifier is undefined because it isn't. remove r1. from your member functions (i.e. anything function starting with Rover::. and you're golden there.
Third, what do you think r1.position[0][0] is going to do? It's just an expression that does nothing. Even position[0][0] is not going to do anything. Perhaps you want to initialize the array somehow but you haven't provided enough information to determine what you're trying to accomplish with it.
Fourth, the member function void Rover::setSpeed(int) has not been declared within the Rover class. Did you forget something? Based on your code it should be
int Rover::getSpeed()
{
return speed;
}
Fifth, void Rover::setSpeed(); doesn't make much sense unless it actually accepts an argument.

Passing Variables Through Functions in C++

So I'm trying to write a basic program in C++ to get the cost of something, the quantity, and calculate the total/subtotal, in three different functions, then display it in main().
Problem is, the variables aren't making it out of the function and I don't know why. I've put output statements inside the functions themselves to check, and the problem only seems to be when I'm trying to pull them out of said functions.
#include <iostream>
using namespace std;
int price(int cost)
{
cout << "What is the cost of the robot?" << endl;
cin >> cost;
if (cost < 1000) //validation
{
cout << "Cost is too low. Setting to $1000." << endl;
cost = 1000;
return cost;
}
return cost;
}
int numRobots(int number)
{
cout << "How many robots are being ordered?" << endl;
cin >> number;
if (number < 50) //validation
{
cout << "We only sell in quantities of 50 or more. Setting quantity to 50." << endl;
number = 50;
return number;
}
return number;
}
void grandTotal(int cost, int number, double &subtotal, double &total)
{
subtotal = (cost * number);
total = (subtotal * .07) + subtotal;
}
int main()
{
int cost = 0;
int number = 0;
double subtotal = 0;
double total = 0;
price(cost);`enter code here`
numRobots(number);
grandTotal(cost, number, subtotal, total);
cout << cost; //testing
cout << number; //outputs
cout << total; //of
cout << subtotal; //variables
system("pause");
return 0;
price(cost);
You are calling a function which returns an int, but you're not storing the int anywhere. You might want to go back to your text book and check the chapter on functions, and how they work. No offense but this is rather basic.
You're doing the same thing with numRobots.
Alternatively, you could pass the parameter by reference and modify it, but imo, that's less easy to understand.
tl;dr;
You should be doing int cost = price(); (there's no reason for the function to take an int as a parameter)
Use returned value or pass parameter by reference or pointer.
1.
int result = numRobots(number);
2.
int numRobots(int& number) {.....}
You need to pass the variables by reference:
int cost = 0;
int number = 0;
price(cost);
numRobots(number);
void price(int& cost)
{
....
}
void numRobots(int& number)
{
....
}
Note the void return type in this case!
Alternatively, you can utilize the return value:
int cost = price(cost);
int number = numRobots(number);
But this method doesn't make much sense because the variable passed as parameter to methods is the same as the one in which the return value is stored!

I have an invalid initialization of reference of type int& from expression of type in passing argument 1

Im trying to lean structures and I think I am doing something wrong when I use the structure and trying to call it into a function.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//Structure
struct Inventory
{
int NumberPartsBin;
};
//Function Prototypes.
void choiceMenu();
void AddParts(int &);
void RemoveParts(int &);
int main()
{
char Election;
int choice;
Inventory Parts = {10};
const int Valve_Choice = 1,
Quit_Choice = 2;
I am trying to to resolve this problem with one item, but I will use arrays for 10 items.
do {
choiceMenu();
cin>> choice;
if (choice >= Valve_Choice & choice <= Quit_Choice)
{
switch(choice){
case Valve_Choice:
cout<<"Enter A for Add Parts or R to Romove Parts";
cin >> Election;
if (Election=='A')
{
AddParts(Parts);// My problem is here
}
if else (Election =='R'){
RemoveParts(Parts);}
else{
cout << "Invalid Entry. Try Again";
cin >> Election; }
break;
case Quit_Choice:
cout<<"Program Ending";
return;
else
{
cout<<"Enter a valid choice!!;
cin >> choice;
}
}
}
while (choice >= Valve_Choice & choice < Quit_Choice);
system("pause");
return 0;
// Bin Choice
void choiceMenu()
{
// We use ofstream to create and write on a text file.
ofstream outputFile;
outputFile.open("C:\\Users\\Alexander MR\\Desktop\\CompanyABCPayRoll.txt");
// The headed of the document.
outputFile << " Inventoy\n";
outputFile << " = = = = = = = = \n";
outputFile << " *Choose the part of your preference.\n";
outputFile << " 1. valves = " << Parts.NumberPartsBin << endl;
outputFile << " 11. Choose 2 to quit the Program" << endl;
outputFile.close();
}
I am not sure of my function either.
my function to add parts
void AddParts(int &Parts1)
{
int Enter1;
Parts1.NumberPartsBin = Parts1.NumberPartsBin + Enter1;
}
My function to remove parts
void RemoveParts(int &Parts2)
{
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
Reading the question with only parts of the code formatted is quite hard. The first thing I saw was:
void RemoveParts( int &Parts2 ) {
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
This makes no sense at all. If Parts2 is an int, then you will never be able to say Parts2.NumberPartsBin. The second thing is int Enter2;. You never give it a value, but in the next line you want to subtract it from something‽
I'm guessing (at least with this function) that you are trying to do something like this:
void RemoveParts( Inventory& inventoryItem, int amountOfParts ) { // inventoryItem is passed by reference, amountOfParts is passed by value
inventoryItem.NumberPartsBin = inventoryItem.NumberPartsBin - amountOfParts;
}
Looking at your code, I'm guessing you're quite new to all of this. I'm no guru, but please:
Capitalize class/struct names and start variable names with a lowercase. ( like parts or election)
If you want to change the value that comes into a function, pass it by reference, but if it is something like an int or a char, simply pass it by value.
p.s. it's if, else if, else and not if else which will otherwise be the next error in your code.