C++ Constructor Delegating Constructors

Introduction

A class can have several constructors.

The code for one constructor can call another of the same class in the initialization list.

The implementation of the first constructor can be:

 
Pool::Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}
{
  std::cout << "Pool constructor 1 called." << std::endl;
}
 

The second constructor creates a Pool object with all sides equal and we can implement it like this:

 
Pool::Pool(double side) : Pool {side, side, side}
{
  std::cout << "Pool constructor 2 called." << std::endl;
}
 
 

Here's a simple illustration of this using the Pool class:

 
class Pool/*from  www.j  a va2  s  .  c om*/
{
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};
 
public:
  // Constructors
  Pool(double lv, double wv, double hv);
  Pool(double side);                         // Constructor for a cube
  Pool() {}                                  // No-arg constructor
 
  double volume();                          // Function to calculate the volume of a pool
};
 
Pool::Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {
  std::cout << "Pool constructor 1 called." << std::endl;
}
 
Pool::Pool(double side) : Pool {side, side, side} {
  std::cout << "Pool constructor 2 called." << std::endl;
}
#include <iostream>
 
int main()
{
  Pool pool1 {2.0, 3.0, 4.0};           // An arbitrary pool
  Pool pool2 {5.0};                     // A pool that is a cube
  std::cout << "pool1 volume = " << pool1.volume() << std::endl;
  std::cout << "pool2 volume = " << pool2.volume() << std::endl;
}



PreviousNext

Related