Defining and using a derived class - C++ Class

C++ examples for Class:Inheritance

Description

Defining and using a derived class

Demo Code

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

class Pool// w w  w .  j  a  v  a 2  s  .co m
{
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 : public Pool
{
private:
  string material;

public:
  Carton(const string desc = "Cardboard") : material {desc}{}     // Constructor
  //  double carton_volume() { return length*width*height; }        // Uncomment for an error!
};

int main()
{
  // Create a Pool object and two Carton objects
  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;

  std::cout << "candyCarton length is " << candyCarton.getLength() << std::endl;

  // Uncomment any of the following for an error...
  // pool.length = 10.0;
  // candyCarton.length = 10.0;
}

Result


Related Tutorials