C++ Class Inheritance Calling base class constructors in a derived class constructor

Description

C++ Class Inheritance Calling base class constructors in a derived class constructor

#include <iostream>
#include <string>                                // For the string class
#include <iostream>
#include <iomanip>

class Pool/*from ww  w . jav a2  s .  co  m*/
{
protected:
  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}
  {  std::cout << "Pool(double, double, double) called.\n"; }

  Pool(double side) : Pool {side, side, side} { std::cout << "Pool(double) called.\n"; }
  Pool() { std::cout << "Pool() called.\n"; }   // 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 : public Pool
{
private:
  string material {"Cardboard"};

public:
  Carton(double lv, double wv, double hv, const string desc) : Pool {lv, wv, hv}, material {desc}
  {
    std::cout << "Carton(double,double,double,string) called.\n";
  }

  Carton(const string desc) : material {desc}
  {  std::cout << "Carton(string) called.\n";  }
  Carton(double side, const string desc) : Pool {side}, material {desc}
  {
    std::cout << "Carton(double,string) called.\n";
  }
  Carton()
  {
    std::cout << "Carton() called.\n";
  }
};

int main()
{
  // Create four Carton objects
  Carton carton1;
  Carton carton2 {"Thin cardboard"};
  Carton carton3 {4.0, 5.0, 6.0, "Plastic"};
  Carton carton4 {2.0, "paper"};

  std::cout << "carton1 volume is " << carton1.volume() << std::endl;
  std::cout << "carton2 volume is " << carton2.volume() << std::endl;
  std::cout << "carton3 volume is " << carton3.volume() << std::endl;
  std::cout << "carton4 volume is " << carton4.volume() << std::endl;
}



PreviousNext

Related