Custom Constructor¶
Constructors: why? (1)¶
Initialization in C
left to the programmer
⟶ sheer number of bugs!
struct point A;
|
A remains uninitialized ⟶ random values |
struct point A = {1,2};
|
|
struct point A;
...
A.x = 1;
A.y = 2;
|
|
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 |
Constructors: Implementation - Inline¶
Short methods are best defined in the class definition itself ⟶ inline
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
membersAssignment in constructor body not possible for
const
members ⟶ initializer list necessary
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 …)
|
|
---|---|
class point
{
public:
point(int x, int y);
};
|
point::point(int x, int y) // <--- note the SCOPE: "point::"
: _x{x}, _y{y}
{}
|