fork download
  1. #include <iostream>
  2.  
  3. template <class ParticularFruit>
  4. struct FruitBase
  5. {
  6. FruitBase(int num) : m_inventory(num) {}
  7.  
  8. float netProfit() const
  9. {
  10. auto && particular_fruit = static_cast<const ParticularFruit &>(*this);
  11. return particular_fruit.totalSellPrice() - particular_fruit.totalCostPrice();
  12. }
  13.  
  14. protected:
  15. int m_inventory;
  16. };
  17.  
  18. struct Apple : FruitBase<Apple>
  19. {
  20. Apple(int num, float unitCostPrice, float unitSellPrice) :
  21. FruitBase(num),
  22. m_unitCostPrice(unitCostPrice),
  23. m_unitSellPrice(unitSellPrice) {}
  24.  
  25. float totalCostPrice() const { return m_inventory * m_unitCostPrice; }
  26. float totalSellPrice() const { return m_inventory * m_unitSellPrice; }
  27.  
  28. private:
  29. float m_unitCostPrice;
  30. float m_unitSellPrice;
  31. };
  32.  
  33. struct Orange : FruitBase<Orange>
  34. {
  35. Orange(int num, float unitCostPrice, float unitSellPrice) :
  36. FruitBase(num),
  37. m_unitCostPrice(unitCostPrice),
  38. m_unitSellPrice(unitSellPrice) {}
  39.  
  40. float totalCostPrice() const { return m_inventory * m_unitCostPrice; }
  41. float totalSellPrice() const { return m_inventory * m_unitSellPrice; }
  42.  
  43. private:
  44. float m_unitCostPrice;
  45. float m_unitSellPrice;
  46. };
  47.  
  48. template <typename Fruit>
  49. void print_net_profit(const Fruit & fruit)
  50. {
  51. std::cout << "Net profit at current prices = $ " << fruit.netProfit() << std::endl;
  52. }
  53.  
  54. int main()
  55. {
  56. Apple apple(100, 4.00, 4.25);
  57. Orange orange(50, 7.00, 7.25);
  58.  
  59. print_net_profit(apple);
  60. print_net_profit(orange);
  61. }
  62.  
Success #stdin #stdout 0s 2884KB
stdin
Standard input is empty
stdout
Net profit at current prices = $ 25
Net profit at current prices = $ 12.5