Constructor: Basics

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;
    }
    // ...
};

Constructors: Implementation - Out-of-Line

Long methods are best defined in the implementation file

point.h: declaration

point.cpp: definition

class point
{
public:
    point(int x, int y);
    // ...
};
point::point(int x, int y)
{
    _x = x;
    _y = y;
}