Custom Constructor

Constructors: why? (1)

Initialization in C

  • left to the programmer

  • sheer number of bugs!

struct point A;

A remains uninitializedrandom values

struct point A = {1,2};

A is initialized with x = 1 and y = 2

struct point A;
...
A.x = 1;
A.y = 2;
  • Definition ⟶ uninitialized

  • Only set at some later point ⟶ error prone

Constructors: why? (2)

Initialization in C++

  • Programmer has no choice

  • Whenever programmer thinks about a point object, they have to think about its value

  • ⟶ initialization error excluded from the beginning

point A;

Compiler error: “void constructor for point not defined”

point A(1,2);

Only possibility to create a point

Constructors: Implementation - Inline

Short methods are best defined in the class definition itself ⟶ inline

point.h: inline definition
class point
{
public:
    point(int x, int y)
    {
        _x = x;
        _y = y;
    }
private:
    int _x;
    int _y;
};
  • Better: using an initializer list for member initialization

  • No difference for non const members

  • Assignment in constructor body not possible for const members ⟶ initializer list necessary

point.h: initializer list
class point
{
public:
    point(int x, int y)
    : _x{x}, _y{y}        // <--- initializer list
    {}                    // <--- empty constructor body
private:
    const int _x;         // <--- note the "const"
    const int _y;         // <--- note the "const"
};

Constructors: Implementation - Out-of-Line

  • Long methods are best defined in the implementation file

  • (class point constructor is not a long method though …)

point.h: declaration

point.cpp: definition

class point
{
public:
    point(int x, int y);
};
point::point(int x, int y)    // <--- note the SCOPE:  "point::"
: _x{x}, _y{y}
{}