What are Constructors - C++ Class

C++ examples for Class:Constructor

Introduction

A class constructor is a special kind of function in a class.

A constructor is called whenever a new instance of the class is created.

It can initialize the new object as it is created and ensure that data members contain valid values.

A class constructor always has the same name as the class.

Pool() is a constructor for the Pool class.

A constructor cannot return a value and has no return type.

If you don't define a constructor for a class, the compiler will create a default constructor.

The Pool class really looks like this with default constructor:

class Pool
{
private:
  double length {1};
  double width {1};
  double height {1};

public:
  // The default constructor that is supplied by the compiler...
  Pool()
  {
    // Empty body so it does nothing...
  }

  // Function to calculate the volume of a pool
  double volume()
  {
    return length*width*height;
  }
};

The default constructor has no parameters.

The following code creates a class with constructor.

Demo Code

#include <iostream>

class Pool {//from   w w w . j  a va2s. com
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  // Constructor
  Pool(double lengthValue, double widthValue, double heightValue) {
    std::cout << "Pool constructor called." << std::endl;
    length = lengthValue;
    width = widthValue;
    height = heightValue;
  }

  // Function to calculate the volume of a pool
  double volume()
  {
    return length*width*height;
  }
};

int main()
{
  Pool firstPool {8.0, 5.0, 4.0};
  double firstPoolVolume {firstPool.volume()};     // Calculate the pool volume
  std::cout << "Volume of Pool object is" << firstPoolVolume << std::endl;
}

Result

If you define a constructor, the compiler won't supply a default constructor.


Related Tutorials