SlideShare une entreprise Scribd logo
1  sur  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.

Contenu connexe

Tendances

Tendances (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
 

Similaire à 2CPP13 - Operator Overloading

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

Similaire à 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++
 

Plus de Michael Heron

Plus de 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
 

Dernier

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Dernier (20)

OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

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.