Constructor: Basics¶
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
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
|
|
---|---|
class point
{
public:
point(int x, int y);
// ...
};
|
point::point(int x, int y)
{
_x = x;
_y = y;
}
|