C++ Class Inheritance Using a derived class copy constructor

Description

C++ Class Inheritance Using a derived class copy constructor

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

class Pool//ww w.  j  a  va2 s. c o  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

  // Copy constructor
  Pool(const Pool& pool) : length {pool.length}, width {pool.width}, height {pool.height}
  {
    std::cout << "Pool copy constructor" << std::endl;
  }

  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";
  }

  // Copy constructor
  Carton(const Carton& carton) : /*Pool {carton}, */ material {carton.material}  // Uncomment for correct operation
  {
    std::cout << "Carton copy constructor" << std::endl;
  }
};

int main()
{
  // Declare and initialize a Carton object
  Carton carton(20.0, 30.0, 40.0, "Glassine board");

  Carton cartonCopy(carton);             // Use copy constructor

  std::cout << "Volume of carton is " << carton.volume() << std::endl
    << "Volume of cartonCopy is " << cartonCopy.volume() << std::endl;
}



PreviousNext

Related