Search code examples
c++inheritanceabstract-classpure-virtual

Inheritance and Pure virtual functions


I'm learning inheritance in c++, and I'm new to abstract pure virtual, base, and derived classes. So I came up with this below code, it works but I'm not sure if I'm implementing the c++ principals correct. Please can someone evaluate the below code for improvement.

#include <iostream>
using namespace std;

class Pizza
{
   private:
       double pCost;
       double pPrice;

   public:
       Pizza(const double& c, const double& p) : pCost(c), pPrice(p){}
       virtual ~Pizza(){}
       virtual double area() = 0;
       virtual double cost() = 0;
       virtual double price () = 0;
       virtual double profit() = 0;
       double getCost() const {return pCost;}
       double getPrice() const {return pPrice;}
};

class CircularPizza : public Pizza
{
   private:
       double radius;

   public:
       CircularPizza(const double& r, const double& c, const double& p)
        : Pizza(c, p), radius(r){}
        virtual ~CircularPizza(){}
        virtual double area(){ return (3.14 * radius * radius);}
        virtual double cost() { return area() * getCost(); }
        virtual double price() { return area() * getPrice(); }
        virtual double profit() { return price() - cost();}
};

Solution

  • If I were to change anything, I'd make cost(), price() and profit() be non-virtual and define them in the base Pizza class.

    This makes sense because they all depend on area -- that's the only thing that CircularPizza is really defining. If you were to make a RectangularPizza class, the cost per area, the price per area, the calculation of profit would be the same. The only thing that would change would be the area itself. Realising this fact is what should lead you to design the classes in the same way, where only the area changes and other code is common to both CircularPizza and RectangularPizza using a base class.