258 Intermediate C Programming
be passed. There is no * after Vector in printVector and the argument is an object. As
a result, the object is copied. If v’s attributes are changed inside printVector, then the
changes will be lost when the function finishes. The syntax for using objects is:
• If p’s value is an address of an object, use p -> x. It is allowed to put a space before
or after -> but no space can be added between - and >.
• If v is an object (not an address), use v.x.
16.3.1 Returning an Object
Can a function return a Vector object? Yes. The following example shows a constructor
function that creates and initializes a new object:
// vector5 .c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
#in clude " vector .h "5
Vector Ve ctor_ constr uct ( i n t a , i n t b , in t c)6
{7
Vector v;8
v. x = a;9
v. y = b;10
v. z = c;11
return v ;12
}13
14
void Vector _print ( Vector v )15
{16
printf (" The vector is (% d, %d , % d) . n ", v .x, v .y, v .z) ;17
}18
19
int main ( i n t argc , char * argv [])20
{21
Vector v1 = Vecto r_con struct (3 , 6 , -2) ;22
Vecto r_print ( v1 );23
return EXIT _SUCCES S ;24
}25
What is the advantage of creating constructor functions? One good reason is that they
make programs easier to read. The three arguments remind programmers that a Vector
object has three attributes. Constructors should guarantee that all attributes are always
initialized. Uninitialized variables can make your programs behave in surprising ways. Before
calling the constructor, v1 is already on the call stack in the frame of the main function.
When the constructor returns the object, the attributes of v are copied to v1’s attributes
one by one. Then, the constructor’s frame is popped and v does not exist any more.
16.3.2 Objects and malloc
Is it possible to create an object that exists in heap memory, instead of stack memory?
Yes. Here is how to do it:
// ve ctormal l oc . c1