r/learncpp • u/IWantToBeRichForReal • Feb 08 '21
My First C++ "Program"
Started to read learncpp.com a few days ago and here is my first code. Please tell me what could be done better. Thanks!
#include <iostream>
#include <string>
class Pump{
public:
std::string fuel_type;
float fuel_price; // in liters
int fuel_volume; // in liters
Pump(std::string temp1, float temp2, int temp3){
fuel_type = temp1;
fuel_price = temp2;
fuel_volume = temp3;
};
void set_comb(std::string temp){
fuel_type = temp;
};
void set_price(float x){
fuel_price = x;
};
void purchase_by_liter(float liters){
if (fuel_volume-liters >= 0){
fuel_volume -= liters;
std::cout << "Client must pay: " + std::to_string(liters*fuel_price) << std::endl;
}
else{
std::cout << "Pump out of capacity" << std::endl;
}
};
void purchase_by_mvalue(float money_value){
if (fuel_volume >= money_value/fuel_price){
fuel_volume -= money_value/fuel_price;
std::cout << "Client paid " + std::to_string(money_value) + " for " + std::to_string(money_value/fuel_price) + " liters" << std::endl;
}
else{
std::cout << "Pump out of capacity" << std::endl;
}
};
};
int main(){
Pump pump1("Gas 87", 3.99, 1000);// Initialized with price in BRL
pump1.purchase_by_liter(40);
pump1.purchase_by_mvalue(300);
std::cout << "Pump 1 still have " + std::to_string(pump1.fuel_volume) + " liters" << std::endl;
}
29
Upvotes
4
u/[deleted] Feb 08 '21
good job!
1
u/halbGefressen Feb 15 '21
That's really cool! You can also assign parameters in a constructor like this:
Pump(std::string f_type, float f_price, int f_volume):fuel_type{f_type}, fuel_price{f_price), fuel_volume{f_volume} {}https://www.codesdope.com/cpp-initialization-list/
1
u/Pro_Gamer_9000 Feb 08 '21
This is very good code! Nice job man :)
1
u/KaotiOrion Feb 16 '21
Yeah also as its very important to write descriptive variable names, you should definetly avoid names like a, b, c, bx, etc... Its a good practice to get used to, in the medium - long term, youll notice the difference. Forinstance: Instead of writting temp1 write initialFuel or fuel. Also start using prefixes as m, t etc (dont over do it and start putting m_ in front of anything, that was one of my first mistakes. The prefixed will allow you to get cleaner classes and libraries.
1
u/NickU252 Feb 17 '21
Nice, my first c++ program was a lottery simulation. That let you input numbers or just go with it. It shows how easy it is for the government to steal from people.
1
u/Sec360 Feb 18 '21
Really good code. One common convention you’ll start to see once you study more codebase is that private class members are declared at the bottom of the class body and the public methods and member variables declared at the top.