Default parameter values in virtual functions - C++ Class

C++ examples for Class:Virtual Function

Description

Default parameter values in virtual functions

Demo Code

#include  <string>
#include  <iostream>

class Pool//w  w w . ja  v  a  2s  .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(int i=5)  const
  {
    std::cout << "Pool parameter = " << i << std::endl;
    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(int i = 50) const override
  {
    std::cout << "Carton parameter = " << i << std::endl;
    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} {}

  // Function  to  calculate volume of  a ToughPack  allowing 15%  for  packing
  double volume(int i = 500) const override
  {
    std::cout << "ToughPack parameter = " << i << std::endl;
    return 0.85*length*width*height;
  }
};

int main(){
  Pool pool {20.0, 30.0, 40.0};
  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

  pool.showVolume();                              // Volume of Pool
  hardcase.showVolume();                         // Volume of ToughPack
  carton.showVolume();                           // Volume of Carton
  std::cout << "hardcase volume is " << hardcase.volume() << std::endl;

  // Now  using a base pointer...
  Pool* pPool {&pool};                              // Points to type Pool
  std::cout << "\npool volume through pPool is " << pPool->volume() << std::endl;
  pPool->showVolume();

  pPool = &hardcase;                             // Points to type ToughPack
  std::cout << "hardcase volume through pPool is " << pPool->volume() << std::endl;
  pPool->showVolume();

  pPool = &carton;                              // Points to  type Carton
  std::cout << "carton volume through pPool is " << pPool->volume() << std::endl;
  pPool->showVolume();
}

Result


Related Tutorials