Lecture 14 - Oct 6, 2023
Summary
In this lecture, we continue on our discussion of dynamic memory allocation of arrays of objects. We also introduce the concept of operator overloading.
Last lecture
Dynamic memory allocation of arrays.
Today
Continue dynamic memory allocation of objects and operator overloading.
Dynamic allocation
Can we dynamically allocate an array of objects? Yes
class Student {
public:
;
string nameint ID;
() { ID = 0; name = ""; }
Student~Student() { cout << "Destructor" << endl; }
};
int main() {
*arr = new Student[3]; // default constructor called 3 times
Student delete [] arr; // destructor called 3 times
return 0; // no destructor will be called without delete
}
Can I have an array of pointers to objects? Yes
int main() {
// no constructors called
** arr2p = new Student* [3];
Student
...
...
for (int i = 0, i < 3; i++) {
[i] = new Student;
arr2p}
...
...
for (int i = 0, i < 3; i++) {
[i]->ID = i + 1;
arr2p}
...
...
for (int i = 0, i < 3; i++) {
delete arr2p[i];
}
...
...
delete [] arr2p;
= NULL; arr2p
Overloading operators (+, -, *, /)
Consider this class
class Complex {
private:
double real;
double img;
public:
() { real = 0.0; img = 0.0; }
Complex(double r, double i) { real = r; img = i; }
Complex};
int main() {
(3,4);
Complex x(5,6);
Complex y;
Complex z= x + y; // I can't do this now
z return 0;
}
Operator overloading allows for z = x + y
.
There are two operators: =
and +
.
Let’s implement a function that does an addition.
x + y
is also equivalent to x.operator+(y)
.
// return type: Complex
// function name: operator+
::operator+(Complex &rhs) {
Complex Complexreturn Complex(real + rhs.real, img + rhs.img);
}
class Complex P{
private:
double real;
double img;
public:
() { real = 0.0; img = 0.0; }
Complex(double r, double i) { real = r; img = i; }
Complex// pass by reference: Complex&
operator+(Complex& rhs);
Complex }
Passing by value will create a copy of the rhs.
This is memory inefficient if the object has many data members.
Pass by value will not create a copy, so it is memory efficient.
Good practices for safety
Pass the object as a constant object
::operator+(const Complex& rhs) {
Complex Complex.real = 0; // compile-time error!
rhsreturn Complex(real + rhs.real, img + rhs.img);
}
Operator+ does not change members of the object
Use const
modifier to prevent changes to members of the object.
::operator+(const Complex& rhs) const {
Complex Complex= 0; // compile-time error!
real return Complex(real + rhs.real, img + rhs.img);
}
Ungraded homework
Solve the exercises of Chapter 4: Pointers and Chapter 5: Dynamic Memory Allocation.