![]() |
CITS2002 Systems Programming |
← prev | next → | ![]() |
![]() |
|||
Initialising the data members of a class with constructorsIn most C11 programs, when introducing a new variable (often near the top of a block of statements) we immediately follow the introduction by multiple statements which initialise the variable.
If a scalar variable, this presents little problem, but for structures or arrays, we must ensure that the initial value is 'suitable', and that we don't miss any values. This is often achieved with an additional function, defined physically 'close' to the definition of the structure or array datatype. In C++, as with most object-oriented languages, we can combine the class's fields (internal variables) with a method to initilise them. This special method, termed a constructor, doesn't require any 'external' code to have knowledge of the implementation of the class, or how its fields are initialised. A constructor is a method that is called when a class instance is created.
CITS2002 Systems Programming, Lecture 23, p8, 17th October 2023.
|