Recap: Account State
Lesson 37 of 48 in Coddy's C++ for Python Developers course.
Challenge
EasyInput: initial nonnegative balance then signed operations. Positive operations deposit; negative operations attempt withdrawal without overdraft; zero does nothing. Account.apply returns success and preserves balance for rejected operations. Print final balance and rejected count.
Editable modules: Account.cpp, Account.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.
Try it yourself
#include "Account.hpp"
#include <iostream>
int main(){
{Account a(3),b(9);if(a.apply(-4)||a.balance()!=3||!a.apply(2)||a.balance()!=5||b.balance()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,x,rejected=0;in>>n;Account a(n);while(in>>x)if(!a.apply(x))++rejected;std::cout<<a.balance()<<" "<<rejected<<"\n";
}
All lessons in C++ for Python Developers
1C++ Files and Values
Run the C++ FilesStrings and OutputTypes and InitializationDivision and RemaindersBooleans and ConditionsRecap: Parcel Charges4Copies and Algorithms
Value CopiesReferences and MutationFilter and TransformSorting with ComparatorsRecap: Top Unique Scores7Objects and Invariants
Classes and InstancesConstructor InitializationMethods and Const AccessShared Static MembersProtecting InvariantsRecap: Account State2Conditions and Iteration
Text EqualityBranches and RangesCounted IterationEarly Exit and SkippingRecap: Ticket Bands5Functions and Templates
Functions and ReturnsOverloads and DefaultsLambdas and CapturesFunction TemplatesRecap: Tiered Discounts8Composition and Ownership
Composition by ValueVirtual DispatchAbstract Base ContractsMove-only OwnershipRecap: Polymorphic Prices3Standard Containers
Fixed-size ArraysGrowing VectorsMaps and LookupSets and MembershipRecap: Shared Tags6Parsing and Lifetime
Streams and Exact ParsingExceptions and ContractsHeaders and LinkageRAII and Scope ExitRecap: Validate Lines9Project: Library Desk
Project: Book StockProject: Loan FeesPractice on your own: Online C++ compiler