Lecture 4 - Arrays, Pointers and References
Lecture 4 - Arrays, Pointers and References
Lecture Four
Arrays of Objects
1
8/17/2014
Arrays of Objects
(1) For single argument:
(a) For 1D array:
#include <iostream> int main() {
using namespace std; samp ob[4] = {-1. -2. -3, -4};
class samp {
int i; for( int i= 0; i < 4; i++)
public: cout << ob[i].get_i() << ‘ ‘;
samp(int n) { i = n;}; cout << “\n”;
int get_i() { return i;} return 0;
}; }
Arrays of Objects
2
8/17/2014
3
8/17/2014
Advantages of new:
1. Automatically allocate enough memory, no need of sizeof().
2. No explicit type cast is required.
3. Both new and delete can be overloaded.
4. It is possible to initialize the dynamically allocated memory.
return 0;
}
4
8/17/2014
delete [] p;
return 0;
}
References
A reference is an implicit pointer that for all intents and purposes acts like
another name for a variable.
There are three ways that a reference can be used:
A reference can be passed to a function (most important)
A reference can be returned by a function
An independent reference can be created.
Using Pointer, not Reference (only way Using References
used in C for call by reference) #include <iostream>
#include <iostream> Using namespace std;
using namespace std;
void f(int &n);
void f( int *n);
int main(){
int main(){ int i = 0;
int i = 0;
f(i);
f(&i); cout << “value of i:” << i <<’\n’;
cout << “value of i:” << i <<’\n’; return o;
return o; }
}
void f( int &n){
void f( int *n){
n = 100;
*n = 100;
}
}
5
8/17/2014
References
There are several advantages of using reference parameters over their equivalent
pointer alternatives:
1. No longer need to remember to pass the address of an argument.
2. Reference parameters offer a cleaner, more elegant interface than the rather
clumsy explicit pointer mechanism.
3. When an object is passed to a function as a reference, no copy is made.
6
8/17/2014
Returning Reference
Very useful for overloading certain types of operator.
Allow a function to be used on the left side of an assignment statement.
#include <iostream>
using namespace std;
int &f();
int x; BUT
int &f(){
int main() { int x;
f() = 100; return x;
cout << x << ‘\n’; }
return 0;
}
int &f(){
return x;
}
7
8/17/2014
Independent Reference
An independent reference is a reference variable that in all effects is simply another
name for another variable.
Because reference cannot be assigned new values, an independent reference must
be initialized when it is declared.
return 0;
}