Using a reference parameter to call virtual function - C++ Class

C++ examples for Class:Virtual Function

Description

Using a reference parameter to call virtual function

Demo Code

#include  <string>
#include  <iostream>

class Pool//w w w .j a  v  a  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; }
};

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

  // Function  to  calculate volume of  a ToughPack  allowing 15%  for  packing
  double volume()  const override { return 0.85*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;
  }
};
// Global function  to  display  the volume  of  a pool
void  showVolume(const Pool& rPool)
{
  std::cout << "Pool usable volume is " << rPool.volume() << std::endl;
}

int main()
{
  Pool pool {20.0, 30.0, 40.0};                    // A base pool
  ToughPack hardcase {20.0, 30.0, 40.0};         // A derived pool - same size
  Carton carton {20.0, 30.0, 40.0, "plastic"};   // A different derived pool

  showVolume(pool);                               // Display volume of base pool
  showVolume(hardcase);                           // Display volume of derived pool
  showVolume(carton);                             // Display volume of derived pool
}

Result


Related Tutorials