Defining Constructors Outside the Class - C++ Class

C++ examples for Class:Constructor

Description

Defining Constructors Outside the Class

Demo Code

                                                                                                                                 
#include <iostream>
                                                                                                                                 
class Pool {// w w  w.  ja v  a  2s .  co  m
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};
                                                                                                                                 
public:
  // Constructors
  Pool(double lengthValue, double widthValue, double heightValue);
  Pool();                                    // No-arg constructor
  double volume();                          // Function to calculate the volume of a pool
};
                                                                                                                                 
                                                                                                                                 
// Constructor definition
Pool::Pool(double lengthValue, double widthValue, double heightValue) {
  std::cout << "Pool constructor called." << std::endl;
  length = lengthValue;
  width = widthValue;
  height = heightValue;
}
                                                                                                                                 
Pool::Pool() {}                                    // No-arg constructor
                                                                                                                                 
// Function to calculate the volume of a pool
double Pool::volume()
{
  return length*width*height;
}
                                                                                                                                 
int main() {
  Pool firstPool {80.0, 50.0, 40.0};              // Create a pool
  double firstPoolVolume{firstPool.volume()};     // Calculate the pool volume
  std::cout << "Volume of Pool object is" << firstPoolVolume << std::endl;
}

Result


Related Tutorials