Virtual functions using smart pointers - C++ Class

C++ examples for Class:Virtual Function

Description

Virtual functions using smart pointers

Demo Code

#include  <iostream>
#include  <memory>                               // For smart pointers
#include  <vector>                               // For vector
#include  <string>

class Pool/*from   ww w  . j  a va 2  s  .c  o  m*/
{
protected:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {}

  // Function  to  show  the  volume of  an object
  void showVolume() const
  {
    std::cout << "Pool usable volume is " << volume() << std::endl;
  }

  // Function  to  calculate the  volume of  a Pool object
  virtual double volume()  const { return length*width*height; }
};
using  std::string;

class  Carton : public Pool
{
private:
  string material;

public:
  // Constructor  explicitly calling the  base constructor
  Carton(double lv, double wv, double hv, string str = "material") : Pool {lv, wv, hv}
  {
    material = str;
  }

  // Function  to  calculate the  volume of  a Carton object
  double volume() const override
  {
    double vol {(length - 0.5)*(width - 0.5)*(height - 0.5)};
    return vol > 0.0 ? vol : 0.0;
  }
};

class  ToughPack : public Pool
{
public:
  // Constructor
  ToughPack(double lv, double wv, double hv) : Pool {lv, wv, hv} {}

  protected:
  // Function  to  calculate volume of  a ToughPack  allowing 15%  for  packing
  double volume()  const override { return 0.85*length*width*height; }
};

int main()
{
  std::vector<std::shared_ptr<Pool>> pools;
  pools.push_back(std::make_shared<Pool>(20.0, 30.0, 40.0));
  pools.push_back(std::make_shared<ToughPack>(20.0, 30.0, 40.0));
  pools.push_back(std::make_shared<Carton>(20.0, 30.0, 40.0, "plastic"));
  for (auto& p : pools)
    p->showVolume();
}

Result


Related Tutorials