C++ Class Inheritance using declaration to restore public access for inherited member

Description

C++ Class Inheritance using declaration to restore public access for inherited member

#include <iostream>
#include <string>
#include <iostream>
#include <iomanip>

class Pool{/*from  w ww .  j  a  v  a2 s  .c om*/
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  // Constructors
  Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {}
  Pool() = default;                          // No-arg constructor

  double volume() const                     // Function to calculate the volume
  {
    return length*width*height;
  }

  // Accessors
  double getLength() const { return length; }
  double getWidth() const { return width; }
  double getHeight() const { return height; }

  friend std::ostream& operator<<(std::ostream& stream, const Pool& pool);
};

// Stream output for Pool objects
inline std::ostream& operator<<(std::ostream& stream, const Pool& pool)
{
  stream << " Pool(" << std::setw(2) << pool.length << ","
    << std::setw(2) << pool.width << ","
    << std::setw(2) << pool.height << ")";
  return stream;
}

using std::string;

class Carton : private Pool
{
private:
  string material;

public:
  using Pool::volume;                              // Inherit as public
  Carton(const string desc = "Cardboard") : material {desc}{}     // Constructor
};

int main()
{
  Pool pool {40.0, 30.0, 20.0};
  Carton carton;
  Carton candyCarton {"Thin cardboard"};

  // Check them out - sizes first of all
  std::cout << "pool occupies " << sizeof pool << " bytes" << std::endl;
  std::cout << "carton occupies " << sizeof carton << " bytes" << std::endl;
  std::cout << "candyCarton occupies " << sizeof candyCarton << " bytes" << std::endl;

  // Now volumes...
  std::cout << "pool volume is " << pool.volume() << std::endl;
  std::cout << "carton volume is " << carton.volume() << std::endl;
  std::cout << "candyCarton volume is " << candyCarton.volume() << std::endl;


  // Uncomment any of the following for an error...
  //  std::cout << "candyCarton length is " << candyCarton.getLength() << std::endl;
  // pool.length = 10.0;
  // candyCarton.length = 10.0;
}



PreviousNext

Related