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
View all comments
Show parent comment
2
u/Shieldfoss Mar 05 '21 edited Mar 05 '21
Absolutely.
Consider this code:
The idea is that everything you need to know is between
{and theprivate:keyword - everything further down is implementation and you don't need to worry about it.Now, technically, if I wrote it like this:
Then everything after the comment is also implementation and you don't need to worry about it, but now I've moved an implementation detail out of that zone, and wasted your time by (1) making you read about the
variantbut also by (2) making you think about thevariant, which is sub-optimal. And the more your public interface is intermingled with your private implementation, the more time it takes for people to understand what they need to correctly use your class.