C++ Class Inheritance Behavior of inherited functions in a derived class

Description

C++ Class Inheritance Behavior of inherited functions in a derived class

#include  <iostream>

class Pool//w ww.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
  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 { return 0.85*length*width*height; }
};


int main()
{
  Pool pool {20.0, 30.0, 40.0};                   // Define a pool
  ToughPack  hardcase {20.0, 30.0, 40.0};      // Declare tough pool - same size

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

  //std::cout << "hardcase volume is " << hardcase.volume() << std::endl;
  //Pool *pPool {&hardcase};
  //std::cout << "hardcase volume through pPool is " << pPool->volume() << std::endl;
}



PreviousNext

Related