C++ Constructor Using a Constructor Initialization List

Introduction

You can use a constructor initialization list to set the member variable:

 
#include <iostream>
 
class Pool {//  w  w w .j  av  a 2  s.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 using an initializer list
Pool::Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}
{
  std::cout  << "Pool constructor called." << std::endl;
}
 
It is the same as:
 
// Constructor definition
Pool::Pool(double lengthValue, double widthValue, double heightValue) {
  std::cout << "Pool constructor called." << std::endl;
  length = lengthValue;
  width = widthValue;
  height = heightValue;
}



PreviousNext

Related