www.umbc.edu
CMSC202 Computer Science II for Majors
Lecture 13 –
Friends and More
- Dr. Katherine Gibson
Computer Science II for Majors Lecture 13 Friends and More Dr. - - PowerPoint PPT Presentation
CMSC202 Computer Science II for Majors Lecture 13 Friends and More Dr. Katherine Gibson www.umbc.edu Last Class We Covered Linked Lists Traversal Creation Insertion Deletion 2 www.umbc.edu Any Questions from Last
www.umbc.edu
www.umbc.edu
2
www.umbc.edu
www.umbc.edu
4
www.umbc.edu
www.umbc.edu
6
www.umbc.edu
7
www.umbc.edu
8
www.umbc.edu
9
www.umbc.edu
10
www.umbc.edu
www.umbc.edu
12
www.umbc.edu
13
www.umbc.edu
14
www.umbc.edu
15
www.umbc.edu
16
www.umbc.edu
17
www.umbc.edu
18
www.umbc.edu
19
www.umbc.edu
20
www.umbc.edu
21
www.umbc.edu
www.umbc.edu
www.umbc.edu
www.umbc.edu
ClassName::ClassName( const ClassName& obj ) { // code to dynamically allocate data }
www.umbc.edu
Class
string *data2 Object *data3 7 abc Foo bar Class
string *data2 Object *data3
www.umbc.edu
Class
string *data2 Object *data3 7 abc Foo bar Class
string *data2 Object *data3 7 abc Foo bar
www.umbc.edu
class Shoe {
public: Shoe( const Shoe& shoe ); private: int *m_size; string *m_brand;
}; Shoe::Shoe( const Shoe& shoe ) {
m_size = new int( *shoe.m_size ); m_brand = new string( *shoe.m_brand );
}
What’s going on here?
www.umbc.edu
– Define if using dynamic memory
– Prototype:
ClassName& operator=( const ClassName& obj );
– Definition:
ClassName& ClassName::operator=( const ClassName& obj ) { // Deallocate existing memory, if necessary // Allocate new memory }
www.umbc.edu
Shoe& Shoe::operator=( const Shoe& shoe ) { m_size = new int(*shoe.m_size); m_brand = new string(*shoe.m_brand); } // In main() Shoe a(7, "abc"); Shoe b(4, "edf"); b = a;
Shoe a
string *m_brand 7 abc Shoe b
string *m_brand 4 edf What happened to the memory b was pointing to first???
www.umbc.edu
How does the c = b work, when b = a returns nothing??
www.umbc.edu
What’s this? this – a pointer to the current object
www.umbc.edu
class RentalSystem { public: // Assume constructor, other methods… RentalSystem& operator=( const RentalSystem & rs ) private: Customer *m_customers; int m_nbrOfCustomers; }; RentalSystem& RentalSystem::operator=( const RentalSystem & rs ) { delete [] m_customers; m_customers = new Customer[rs.m_nbrOfCustomers]; for (int i = 0; i < rs.m_nbrOfCustomers; ++i) m_customers[i] = rs.m_customers[i]; return *this; }
What happens when you do the following? RentalSystem r; // Add customers… r = r;
www.umbc.edu
RentalSystem& RentalSystem::operator=( const RentalSystem & rs ) { // If this is NOT the same object as rs if ( this != &rs ) { delete [] m_customers; m_customers = new Customer[rs.m_nbrOfCustomers]; for (int i = 0; i < rs.m_nbrOfCustomers; ++i) m_customers[i] = rs.m_customers[i]; } return *this; }
www.umbc.edu
35