Menu
CoddyTech

Recap: Polymorphic Prices

Lesson 42 of 48 in Coddy's C++ for Rust Developers course.

challenge icon

Challenge

Easy

Input: nonnegative unit cost, quantity, and integer discount percent from 0 to 100. Price is abstract. FullPrice returns unit times quantity; DiscountPrice reduces that by percent, truncating fractional units. Driver invokes both through Price references.

Editable modules: Price.cpp, Price.hpp, FullPrice.cpp, FullPrice.hpp, DiscountPrice.cpp, DiscountPrice.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 "Price.hpp"
#include "FullPrice.hpp"
#include "DiscountPrice.hpp"
#include <iostream>
int main(){
{FullPrice f;DiscountPrice d(25);const Price& p=d;if(f.cost(3,4)!=12||p.cost(4,4)!=12||p.cost(7,2)!=10)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 u,q,p;in>>u>>q>>p;FullPrice a;DiscountPrice b(p);const Price& x=a;const Price& y=b;std::cout<<x.cost(u,q)<<" "<<y.cost(u,q)<<"\n";
}

All lessons in C++ for Rust Developers

Practice on your own: Online C++ compiler