Destructors in a class hierarchy - C++ Class

C++ examples for Class:Inheritance

Description

Destructors in a class hierarchy

Demo Code

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

class Pool/* ww w.  j  a va2s.  c om*/
{
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;
  }

  // Destructor
  ~Pool() { std::cout << "Pool destructor" << std::endl; }

  // 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}
  {
    std::cout << "Carton copy constructor" << std::endl;
  }

  // Destructor
  ~Carton()
  {
    std::cout << "Carton destructor. Material = " << material << std::endl;
  }
};
int main()
{
  Carton carton;
  Carton candyCarton {50.0, 30.0, 20.0, "Thin cardboard"};

  std::cout << "carton volume is " << carton.volume() << std::endl;
  std::cout << "candyCarton volume is " << candyCarton.volume() << std::endl;
}

Result


Related Tutorials