Array, Pointers and References
Contents
• Arrays of Objects
• Using Pointers to Objects
• The this Pointer
• Using new AND delete
• References
• Exercises
Arrays of Objects
• Objects are variables and have the same capabilities and attributes as any
other type of variable.
• It is perfectly acceptable for objects to be arrayed.
Using Pointers to Objects
• Objects can be accessed via pointers.
• When an object pointer is incremented, it points to the next object.
• When an object pointer is decremented, it points to the previous object.
The this Pointer
• C++ contains a special pointer that is called this.
• this is a pointer that is automatically passed to any member function when it is
called, and it is a pointer to the object that generates the call.
• For example, given statement,
• ob.f1() //assume that ob is an object
• The function f1() is automatically passed a pointer to ob – which is the object that
invokes the call. The pointer is referred to as this.
• Only member functions are passed a this pointer. A friend function does not have a
this pointer.
Using new AND delete
• In C++, you can allocate memory using new and release it using delete.
• new is an operator that returns a pointer to dynamically allocated memory
that is large enough to hold an object.
• delete releases that memory when it is no longer needed.
• Dynamically allocated objects can be given initial values.
• Dynamically allocated arrays can be created. A dynamic array can not be
initialized.
References
• A reference is an implicit pointer that for all intents and purposes acts like
another name for a variable.
• The most important use of a reference is as a parameter to a function.
• When you pass the object by reference, no copy is made, and therefore its
destructor function is not called when the function returns.
• A function can return a reference.
Exercises
• Create a Student class with attributes like name, roll number, and an array of
marks. Implement methods to calculate the average and display student
information.
• Design a Car class with attributes like make, model, and year. Dynamically
allocate memory for an array of Car objects.
• Implement a swapping function that takes two Book objects by reference
and swaps their attributes.