2.7.  Constructors

[ fromfile: constructors.xml id: constructors ]

  ClassName::ClassName( parameterList )
          :initList 1
          {
             constructor body
          }

  

1

Optional- but important. Do not omit this even though the compiler does not care.

Example 2.7. src/ctor/complex.h

#include <string>
using namespace std;

class Complex {
 public:
    Complex(double realPart, double imPart);
    Complex(double realPart);
    Complex();
    string toString() const;
 private:
    double m_R, m_I;
};


Example 2.8 contains the implementation with some client code.

Example 2.8. src/ctor/complex.cpp

#include "complex.h"
#include <iostream>
#include <sstream>
using namespace std;

Complex::Complex(double realPart, double imPart)
    :   m_R(realPart), m_I(imPart)  1
{ 
    cout << "complex(" << m_R << "," << m_I << ")" << endl;
}

Complex::Complex(double realPart) : 
    m_R(realPart), m_I(0) {
}

Complex::Complex() : m_R(0.0), m_I(0.0) {

}

string Complex::toString() const {
    ostringstream strbuf;
    strbuf << '(' << m_R << ", " << m_I << ')';
    return strbuf.str();
}

int main() {
    Complex C1;
    Complex C2(3.14);
    Complex C3(6.2, 10.23);
    cout << C1.toString() << '\t' << C2.toString() 
         << C3.toString() << endl;
}
       

1

Member initialization list.


   double x, y;
   cout << x << '\t' << y << endl;
[Important]Question

What would you expect to be the output of that code?

  Complex(double realPart, double imPart) {
     m_R = realPart;
     m_I = imPart;
  }
  Square::Square(const Point& ul, const Point& lr) {
     m_UpperLeft = ul;
     m_LowerRight = lr;
  }