SlideShare ist ein Scribd-Unternehmen logo
1 von 21
OPERATOR
OVERLOADING
Michael Heron
Introduction
• Today’s lecture is about operator overloading.
• Here be dragons.
• This is not a facility of which I am very fond…
• … coverage in the module is provided for completeness.
• It is a facility that does not exist in Java or C#.
• It is very powerful, very useful, but one of the easiest
ways to develop virtually unreadable code.
Operator Overloading
• Operator overloading is the process of providing object
specific functionality for the base operators:
• +
• -
• /
• *
• You can overload these to allow you to, for example,
divide objects by each other or multiply them together.
• In Java if you wish to do this, you must define methods for the
operation.
The Structure of an Operator
• All operators, fundamentally, do two things:
• Operate on one or more values (known as operands)
• Return a value
• Consider the example:
• int num = 4 + 5
• Operator is +
• Operands and 4 and 5
• Returns the sum of the two operands - 9
Overloading an Operator
• In C++, an overloaded operator is just another method
defined in the class.
• As with a constructor, it has a specific naming convention.
• The method name is the keyword operator followed by
the operator symbol:
• operator+, as an example.
• These must be prototyped as usual in the class definition.
Overloaded Operator
class Employee {
private:
int payscale;
public:
int query_payscale();
void set_payscale (int p);
virtual bool can_hire_and_fire();
virtual bool has_authority (string);
int operator+ (int);
}
int Employee::operator+ (int num) {
payscale += num;
return payscale;
}
Limitations
• Overloaded operators will not work with pointers.
• They work only with value objects.
• If you want to use an overloaded operator on a pointer, you must
explicitly dereference it first.
• You can only redefine pointers for classes you write
yourself.
• The left hand operand is always the left hand side of the
operator.
• The right hand side can be any data type.
Applicability
• Almost any operator can be overloaded in C++.
• Including array notation and the new keyword.
• In most cases, the overloaded operators are just for
convenience.
• A syntactic nicety.
• Which comes with all sorts of problems.
• However, it is often necessary to overload the = operator.
Dynamic Data
• C++ allows us to pass by both reference and value.
• For objects and primitive data types.
• Java allows only pass by reference.
• What happens in C++ if we pass by value an object
containing pointers?
• It creates only a shallow copy of the object.
• It copies only the object’s data fields.
• The pointer in the copy will point to the original dynamic
memory.
Shallow Copies
• This is known as a shallow copy:
• Person a;
• Person b = a;
• Both a and b make use of the same dynamic data.
• C++ gives us two ways of dealing with this.
• Overloading the assignment operator
• Defining a copy constructor.
• They have the same basic intention.
• Assignment operators are used when an object already exists.
• Copy constructors are used when a new object must be created.
Copy Constructors
• There’s nothing syntactically special about a copy
constructor.
• It’s a constructor that takes a configured object as a parameter.
• This object must be passed by reference
• Where it differs is in how it works.
• In it you can handle the creation and manipulation of data fields as
you see fit.
Copy Constructors
• There are three point when a copy constructor will be
called.
• When an object is created from another object of the same type.
• When an object is passed by value as a parameter to a function.
• When an object is returned from a function.
• If a copy constructor is not defined, one will be created by
the compiler.
• This is fine if you’re not working with dynamic data.
Stack Example
class Stack {
private:
int size;
int *elements;
public:
void push(int);
int pop();
Stack();
};
#include "Stack.h"
Stack::Stack() {
elements = new int [100];
size = 0;
}
int Stack::pop() {
int popped;
if (size == 0) {
return -1;
}
popped = elements[size-1];
size -= 1;
return popped;
}
void Stack::push(int val) {
if (size == 100) {
return;
}
elements[size] = val;
size += 1;
}
Stack Example
#include <iostream>
#include "Stack.h"
using namespace std;
int main() {
Stack my_stack;
Stack my_second_stack = my_stack;
my_stack.push (3);
my_stack.push (2);
my_stack.push (1);
cout << my_stack.pop() << ", " << my_stack.pop() << ", "
<< my_stack.pop() << endl;
my_second_stack.push (9);
my_stack.push (8);
cout << my_second_stack.pop() << endl;
return 1;
}
Copy Constructor
class Stack {
private:
int size;
int *elements;
public:
void push(int);
int pop();
Stack();
Stack (Stack&);
};
Stack::Stack (Stack& copy) {
elements = new int[100];
for (int i = 0; i < copy.size; i++) {
elements[i] = copy.elements[i];
}
}
Copy Constructor
• This only works when we create an object from an
existing object:
• Stack my_second_stack = my_stack
• Not when we create an object afterwards:
• Stack my_second_stack;
• my_second_stack = my_stack
• For the latter case, we must provided an overloaded
assignment operator.
Overloaded =
class Stack {
private:
int size;
int *elements;
public:
void push(int);
int pop();
Stack();
Stack (Stack&);
Stack operator= (Stack&);
};
Stack Stack::operator =(Stack& copy) {
size = copy.size;
elements = new int[100];
for (int i = 0; i < size; i++) {
elements[i] = copy.elements[i];
}
return (*this);
}
Notes on Both Approaches
• You can access private data members of the parameter
passed in.
• this in c++ used to provide a reference to the object in
which the code is defined.
• Used to return a reference to the object.
• Code suffers from memory leaks!
• Must explicitly delete dynamic memory before assigning new
objects.
Deep Copies
• In both cases, the two approaches are used to provide
deep copies of an object.
• We don’t just copy a pointer reference, we copy the contents being
pointed to.
• This ensures that our references are clean and not
overlapping.
• These kind of errors are extremely subtle.
• Need to do this when dynamic data is being stored.
Copy versus Assignment
• Copy constructors:
• Create a new object
• By copying an old object
• Called when objects are passed or returned by value.
• Like all constructors, does not return a value.
• Overloaded =:
• Copies an existing object onto another existing object.
• Returns a reference to the newly setup object.
• When working with dynamic data, you need to provide both!
Summary
• You can overload operators in C++
• But you know… don’t.
• The only time this is needed and appropriate is
overloading the equals operator.
• Shallow copies of objects cause side-effects.
• And these side-effects are often very difficult to detect.
• Deep copies using copy constructors and overloaded
operators are required.

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
Java Tutorial Lab 5
Java Tutorial Lab 5Java Tutorial Lab 5
Java Tutorial Lab 5
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Files io
Files ioFiles io
Files io
 
List
ListList
List
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmap
 
Knockoutjs Part 3 Computed Observables
Knockoutjs Part 3 Computed ObservablesKnockoutjs Part 3 Computed Observables
Knockoutjs Part 3 Computed Observables
 
DotNet programming & Practices
DotNet programming & PracticesDotNet programming & Practices
DotNet programming & Practices
 
Operators in mule dataweave
Operators in mule dataweaveOperators in mule dataweave
Operators in mule dataweave
 
Java Arrays and DateTime Functions
Java Arrays and DateTime FunctionsJava Arrays and DateTime Functions
Java Arrays and DateTime Functions
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard Library
 
Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
 
Collections
CollectionsCollections
Collections
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
 

Ähnlich wie 2CPP13 - Operator Overloading

Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 

Ähnlich wie 2CPP13 - Operator Overloading (20)

C++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversionC++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversion
 
Unit ii
Unit iiUnit ii
Unit ii
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
Aspdot
AspdotAspdot
Aspdot
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
 
C++ training
C++ training C++ training
C++ training
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 

Mehr von Michael Heron

Mehr von Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Kürzlich hochgeladen (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

2CPP13 - Operator Overloading

  • 2. Introduction • Today’s lecture is about operator overloading. • Here be dragons. • This is not a facility of which I am very fond… • … coverage in the module is provided for completeness. • It is a facility that does not exist in Java or C#. • It is very powerful, very useful, but one of the easiest ways to develop virtually unreadable code.
  • 3. Operator Overloading • Operator overloading is the process of providing object specific functionality for the base operators: • + • - • / • * • You can overload these to allow you to, for example, divide objects by each other or multiply them together. • In Java if you wish to do this, you must define methods for the operation.
  • 4. The Structure of an Operator • All operators, fundamentally, do two things: • Operate on one or more values (known as operands) • Return a value • Consider the example: • int num = 4 + 5 • Operator is + • Operands and 4 and 5 • Returns the sum of the two operands - 9
  • 5. Overloading an Operator • In C++, an overloaded operator is just another method defined in the class. • As with a constructor, it has a specific naming convention. • The method name is the keyword operator followed by the operator symbol: • operator+, as an example. • These must be prototyped as usual in the class definition.
  • 6. Overloaded Operator class Employee { private: int payscale; public: int query_payscale(); void set_payscale (int p); virtual bool can_hire_and_fire(); virtual bool has_authority (string); int operator+ (int); } int Employee::operator+ (int num) { payscale += num; return payscale; }
  • 7. Limitations • Overloaded operators will not work with pointers. • They work only with value objects. • If you want to use an overloaded operator on a pointer, you must explicitly dereference it first. • You can only redefine pointers for classes you write yourself. • The left hand operand is always the left hand side of the operator. • The right hand side can be any data type.
  • 8. Applicability • Almost any operator can be overloaded in C++. • Including array notation and the new keyword. • In most cases, the overloaded operators are just for convenience. • A syntactic nicety. • Which comes with all sorts of problems. • However, it is often necessary to overload the = operator.
  • 9. Dynamic Data • C++ allows us to pass by both reference and value. • For objects and primitive data types. • Java allows only pass by reference. • What happens in C++ if we pass by value an object containing pointers? • It creates only a shallow copy of the object. • It copies only the object’s data fields. • The pointer in the copy will point to the original dynamic memory.
  • 10. Shallow Copies • This is known as a shallow copy: • Person a; • Person b = a; • Both a and b make use of the same dynamic data. • C++ gives us two ways of dealing with this. • Overloading the assignment operator • Defining a copy constructor. • They have the same basic intention. • Assignment operators are used when an object already exists. • Copy constructors are used when a new object must be created.
  • 11. Copy Constructors • There’s nothing syntactically special about a copy constructor. • It’s a constructor that takes a configured object as a parameter. • This object must be passed by reference • Where it differs is in how it works. • In it you can handle the creation and manipulation of data fields as you see fit.
  • 12. Copy Constructors • There are three point when a copy constructor will be called. • When an object is created from another object of the same type. • When an object is passed by value as a parameter to a function. • When an object is returned from a function. • If a copy constructor is not defined, one will be created by the compiler. • This is fine if you’re not working with dynamic data.
  • 13. Stack Example class Stack { private: int size; int *elements; public: void push(int); int pop(); Stack(); }; #include "Stack.h" Stack::Stack() { elements = new int [100]; size = 0; } int Stack::pop() { int popped; if (size == 0) { return -1; } popped = elements[size-1]; size -= 1; return popped; } void Stack::push(int val) { if (size == 100) { return; } elements[size] = val; size += 1; }
  • 14. Stack Example #include <iostream> #include "Stack.h" using namespace std; int main() { Stack my_stack; Stack my_second_stack = my_stack; my_stack.push (3); my_stack.push (2); my_stack.push (1); cout << my_stack.pop() << ", " << my_stack.pop() << ", " << my_stack.pop() << endl; my_second_stack.push (9); my_stack.push (8); cout << my_second_stack.pop() << endl; return 1; }
  • 15. Copy Constructor class Stack { private: int size; int *elements; public: void push(int); int pop(); Stack(); Stack (Stack&); }; Stack::Stack (Stack& copy) { elements = new int[100]; for (int i = 0; i < copy.size; i++) { elements[i] = copy.elements[i]; } }
  • 16. Copy Constructor • This only works when we create an object from an existing object: • Stack my_second_stack = my_stack • Not when we create an object afterwards: • Stack my_second_stack; • my_second_stack = my_stack • For the latter case, we must provided an overloaded assignment operator.
  • 17. Overloaded = class Stack { private: int size; int *elements; public: void push(int); int pop(); Stack(); Stack (Stack&); Stack operator= (Stack&); }; Stack Stack::operator =(Stack& copy) { size = copy.size; elements = new int[100]; for (int i = 0; i < size; i++) { elements[i] = copy.elements[i]; } return (*this); }
  • 18. Notes on Both Approaches • You can access private data members of the parameter passed in. • this in c++ used to provide a reference to the object in which the code is defined. • Used to return a reference to the object. • Code suffers from memory leaks! • Must explicitly delete dynamic memory before assigning new objects.
  • 19. Deep Copies • In both cases, the two approaches are used to provide deep copies of an object. • We don’t just copy a pointer reference, we copy the contents being pointed to. • This ensures that our references are clean and not overlapping. • These kind of errors are extremely subtle. • Need to do this when dynamic data is being stored.
  • 20. Copy versus Assignment • Copy constructors: • Create a new object • By copying an old object • Called when objects are passed or returned by value. • Like all constructors, does not return a value. • Overloaded =: • Copies an existing object onto another existing object. • Returns a reference to the newly setup object. • When working with dynamic data, you need to provide both!
  • 21. Summary • You can overload operators in C++ • But you know… don’t. • The only time this is needed and appropriate is overloading the equals operator. • Shallow copies of objects cause side-effects. • And these side-effects are often very difficult to detect. • Deep copies using copy constructors and overloaded operators are required.