SlideShare a Scribd company logo
Operator
Overloading
Case Study: Array
// Array class for storing arrays of integers.
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
using std::ostream;
using std::istream;
class Array
{
friend ostream &operator<<( ostream &, const Array & );
friend istream &operator>>( istream &, Array & );
public:
Array( int = 10 ); // default constructor
Array( const Array & ); // copy constructor
~Array(); // destructor
int getSize() const; // return size
Array.h
const Array &operator=( const Array & ); // assignment operator
bool operator==( const Array & ) const; // equality operator
// inequality operator; returns opposite of == operator
bool operator!=( const Array &right ) const
{
return ! ( *this == right ); // invokes Array::operator==
} // end function operator!=
// subscript operator for non-const objects returns modifiable lvalue
int &operator[]( int );
// subscript operator for const objects returns rvalue
int operator[]( int ) const;
private:
int size; // pointer-based array size
int *ptr; // pointer to first element of pointer-based array
}; // end class Array
#endif
Array.h
#include "Array.h"
int main()
{
Array integers1( 7 ); // seven-element Array
Array integers2; // 10-element Array by default
// print integers1 size and contents
cout << "Size of Array integers1 is "
<< integers1.getSize()
<< "nArray after initialization:n" << integers1;
// print integers2 size and contents
cout << "nSize of Array integers2 is "
<< integers2.getSize()
<< "nArray after initialization:n" << integers2;
// input and print integers1 and integers2
cout << "nEnter 17 integers:" << endl;
cin >> integers1 >> integers2;
Main
cout << "nAfter input, the Arrays contain:n"
<< "integers1:n" << integers1
<< "integers2:n" << integers2;
// use overloaded inequality (!=) operator
cout << "nEvaluating: integers1 != integers2" << endl;
if ( integers1 != integers2 )
cout << "integers1 and integers2 are not equal" << endl;
// create Array integers3 using integers1 as an
// initializer; print size and contents
Array integers3( integers1 ); // invokes copy constructor
cout << "nSize of Array integers3 is "
<< integers3.getSize()
<< "nArray after initialization:n" << integers3;
Main
// use overloaded assignment (=) operator
cout << "nAssigning integers2 to integers1:" << endl;
integers1 = integers2; // note target Array is smaller
cout << "integers1:n" << integers1
<< "integers2:n" << integers2;
// use overloaded equality (==) operator
cout << "nEvaluating: integers1 == integers2" << endl;
if ( integers1 == integers2 )
cout << "integers1 and integers2 are equal" << endl;
// use overloaded subscript operator to create rvalue
cout << "nintegers1[5] is " << integers1[ 5 ];
Main
// use overloaded subscript operator to create lvalue
cout << "nnAssigning 1000 to integers1[5]" << endl;
integers1[ 5 ] = 1000;
cout << "integers1:n" << integers1;
// attempt to use out-of-range subscript
cout << "nAttempt to assign 1000 to integers1[15]" << endl;
integers1[ 15 ] = 1000; // ERROR: out of range
return 0;
} // end main
Main
Array::Array( int arraySize )
{
size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize
ptr = new int[ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ )
ptr[ i ] = 0; // set pointer-based array element
} // end Array default constructor
// copy constructor for class Array;
// must receive a reference to prevent infinite recursion
Array::Array( const Array &arrayToCopy )
: size( arrayToCopy.size )
{
ptr = new int[ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ )
ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object
} // end Array copy constructor
Array.cpp
Array::Array( int arraySize )
{
size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize
ptr = new int[ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ )
ptr[ i ] = 0; // set pointer-based array element
} // end Array default constructor
// copy constructor for class Array;
// must receive a reference to prevent infinite recursion
Array::Array( const Array &arrayToCopy )
: size( arrayToCopy.size )
{
ptr = new int[ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ )
ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object
} // end Array copy constructor
Array.cpp: Constructors
// destructor for class Array
Array::~Array()
{
delete [] ptr; // release pointer-based array space
} // end destructor
// return number of elements of Array
int Array::getSize() const
{
return size; // number of elements in Array
} // end function getSize
Array.cpp: Destructor
// overloaded assignment operator;
// const return avoids: ( a1 = a2 ) = a3
const Array &Array::operator=( const Array &right )
{
if ( &right != this ) // avoid self-assignment
{
// for Arrays of different sizes, deallocate original
// left-side array, then allocate new left-side array
if ( size != right.size )
{
delete [] ptr; // release space
size = right.size; // resize this object
ptr = new int[ size ]; // create space for array copy
} // end inner if
for ( int i = 0; i < size; i++ )
ptr[ i ] = right.ptr[ i ]; // copy array into object
} // end outer if
return *this; // enables x = y = z, for example
} // end function operator=
Array.cpp: Assignment
// determine if two Arrays are equal and
// return true, otherwise return false
bool Array::operator==( const Array &right ) const
{
if ( size != right.size )
return false; // arrays of different number of elements
for ( int i = 0; i < size; i++ )
if ( ptr[ i ] != right.ptr[ i ] )
return false; // Array contents are not equal
return true; // Arrays are equal
} // end function operator==
Array.cpp: Equality
// overloaded subscript operator for non-const Arrays;
// reference return creates a modifiable lvalue
int &Array::operator[]( int subscript )
{
// check for subscript out-of-range error
if ( subscript < 0 || subscript >= size )
{
cerr << "nError: Subscript " << subscript
<< " out of range" << endl;
exit( 1 ); // terminate program; subscript out of range
} // end if
return ptr[ subscript ]; // reference return
} // end function operator[]
Array.cpp: Subscript
// overloaded subscript operator for const Arrays
// const reference return creates an rvalue
int Array::operator[]( int subscript ) const
{
// check for subscript out-of-range error
if ( subscript < 0 || subscript >= size )
{
cerr << "nError: Subscript " << subscript
<< " out of range" << endl;
exit( 1 ); // terminate program; subscript out of range
} // end if
return ptr[ subscript ]; // returns copy of this element
} // end function operator[]
Array.cpp: Subscript
// overloaded output operator for class Array
ostream &operator<<( ostream &output, const Array &a )
{
int i;
// output private ptr-based array
for ( i = 0; i < a.size; i++ )
{
output << setw( 12 ) << a.ptr[ i ];
if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output
output << endl;
} // end for
if ( i % 4 != 0 ) // end last line of output
output << endl;
return output; // enables cout << x << y;
} // end function operator<<
Stream insertion
// overloaded input operator for class Array;
// inputs values for entire Array
istream &operator>>( istream &input, Array &a )
{
for ( int i = 0; i < a.size; i++ )
input >> a.ptr[ i ];
return input; // enables cin >> x >> y;
} // end function
Stream Extraction

More Related Content

What's hot

Advanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriterAdvanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriter
Weaveworks
 
F[5]
F[5]F[5]
Hive - ORIEN IT
Hive - ORIEN ITHive - ORIEN IT
Hive - ORIEN IT
ORIEN IT
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
SynapseindiaComplaints
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
Ximing Dai
 
Namespaces
NamespacesNamespaces
Namespaces
zindadili
 
Chapter iii(advance function)
Chapter iii(advance function)Chapter iii(advance function)
Chapter iii(advance function)
Chhom Karath
 
Groovy
GroovyGroovy
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Abimbola Idowu
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
Romain Francois
 
From OCaml To Javascript At Skydeck
From OCaml To Javascript At SkydeckFrom OCaml To Javascript At Skydeck
From OCaml To Javascript At Skydeck
Jake Donham
 
Python Yield
Python YieldPython Yield
Python Yield
yangjuven
 
F[1]
F[1]F[1]
F sh3tdkeq
F sh3tdkeqF sh3tdkeq
F sh3tdkeq
Lokesh Lio M
 
Curso de Node.js e MongoDB - 16
Curso de Node.js e MongoDB - 16Curso de Node.js e MongoDB - 16
Curso de Node.js e MongoDB - 16
Luiz Duarte
 
PHP in 2018 - Q1 - AFUP Limoges
PHP in 2018 - Q1 - AFUP LimogesPHP in 2018 - Q1 - AFUP Limoges
PHP in 2018 - Q1 - AFUP Limoges
✅ William Pinaud
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
piyush Kumar Sharma
 
Computer notes - Reference Variables –II
Computer notes  - Reference Variables –IIComputer notes  - Reference Variables –II
Computer notes - Reference Variables –II
ecomputernotes
 
__array_function__ conceptual design & related concepts
__array_function__ conceptual design & related concepts__array_function__ conceptual design & related concepts
__array_function__ conceptual design & related concepts
Ralf Gommers
 

What's hot (20)

Advanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriterAdvanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriter
 
F[5]
F[5]F[5]
F[5]
 
Hive - ORIEN IT
Hive - ORIEN ITHive - ORIEN IT
Hive - ORIEN IT
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
Namespaces
NamespacesNamespaces
Namespaces
 
Chapter iii(advance function)
Chapter iii(advance function)Chapter iii(advance function)
Chapter iii(advance function)
 
Groovy
GroovyGroovy
Groovy
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
From OCaml To Javascript At Skydeck
From OCaml To Javascript At SkydeckFrom OCaml To Javascript At Skydeck
From OCaml To Javascript At Skydeck
 
Python Yield
Python YieldPython Yield
Python Yield
 
F[1]
F[1]F[1]
F[1]
 
F sh3tdkeq
F sh3tdkeqF sh3tdkeq
F sh3tdkeq
 
Curso de Node.js e MongoDB - 16
Curso de Node.js e MongoDB - 16Curso de Node.js e MongoDB - 16
Curso de Node.js e MongoDB - 16
 
PHP in 2018 - Q1 - AFUP Limoges
PHP in 2018 - Q1 - AFUP LimogesPHP in 2018 - Q1 - AFUP Limoges
PHP in 2018 - Q1 - AFUP Limoges
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Computer notes - Reference Variables –II
Computer notes  - Reference Variables –IIComputer notes  - Reference Variables –II
Computer notes - Reference Variables –II
 
__array_function__ conceptual design & related concepts
__array_function__ conceptual design & related concepts__array_function__ conceptual design & related concepts
__array_function__ conceptual design & related concepts
 

Similar to Object oriented programming; operator overloading array

Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more
steviesellars
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
UmairMughal74
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
fantoosh1
 
Js hacks
Js hacksJs hacks
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
BANSALANKIT1077
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
arjunhassan8
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
Sperasoft
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
arri2009av
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdf
angelfragranc
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
nageswara1958
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
mohammadirfan136964
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
mohdjakirfb
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 

Similar to Object oriented programming; operator overloading array (20)

Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
 
Js hacks
Js hacksJs hacks
Js hacks
 
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Link list
Link listLink list
Link list
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdf
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 

More from Syed Zaid Irshad

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
Syed Zaid Irshad
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
Syed Zaid Irshad
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
Syed Zaid Irshad
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
Syed Zaid Irshad
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
Syed Zaid Irshad
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
Syed Zaid Irshad
 
C Language
C LanguageC Language
C Language
Syed Zaid Irshad
 
Flowchart
FlowchartFlowchart
Flowchart
Syed Zaid Irshad
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
Syed Zaid Irshad
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
Syed Zaid Irshad
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
Syed Zaid Irshad
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
Syed Zaid Irshad
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
Syed Zaid Irshad
 
Data Communication
Data CommunicationData Communication
Data Communication
Syed Zaid Irshad
 
Information Networks
Information NetworksInformation Networks
Information Networks
Syed Zaid Irshad
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
Syed Zaid Irshad
 

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
shahdabdulbaset
 
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
amsjournal
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 

Recently uploaded (20)

官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
 
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
UNLOCKING HEALTHCARE 4.0: NAVIGATING CRITICAL SUCCESS FACTORS FOR EFFECTIVE I...
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 

Object oriented programming; operator overloading array

  • 3. // Array class for storing arrays of integers. #ifndef ARRAY_H #define ARRAY_H #include <iostream> using std::ostream; using std::istream; class Array { friend ostream &operator<<( ostream &, const Array & ); friend istream &operator>>( istream &, Array & ); public: Array( int = 10 ); // default constructor Array( const Array & ); // copy constructor ~Array(); // destructor int getSize() const; // return size Array.h
  • 4. const Array &operator=( const Array & ); // assignment operator bool operator==( const Array & ) const; // equality operator // inequality operator; returns opposite of == operator bool operator!=( const Array &right ) const { return ! ( *this == right ); // invokes Array::operator== } // end function operator!= // subscript operator for non-const objects returns modifiable lvalue int &operator[]( int ); // subscript operator for const objects returns rvalue int operator[]( int ) const; private: int size; // pointer-based array size int *ptr; // pointer to first element of pointer-based array }; // end class Array #endif Array.h
  • 5. #include "Array.h" int main() { Array integers1( 7 ); // seven-element Array Array integers2; // 10-element Array by default // print integers1 size and contents cout << "Size of Array integers1 is " << integers1.getSize() << "nArray after initialization:n" << integers1; // print integers2 size and contents cout << "nSize of Array integers2 is " << integers2.getSize() << "nArray after initialization:n" << integers2; // input and print integers1 and integers2 cout << "nEnter 17 integers:" << endl; cin >> integers1 >> integers2; Main
  • 6. cout << "nAfter input, the Arrays contain:n" << "integers1:n" << integers1 << "integers2:n" << integers2; // use overloaded inequality (!=) operator cout << "nEvaluating: integers1 != integers2" << endl; if ( integers1 != integers2 ) cout << "integers1 and integers2 are not equal" << endl; // create Array integers3 using integers1 as an // initializer; print size and contents Array integers3( integers1 ); // invokes copy constructor cout << "nSize of Array integers3 is " << integers3.getSize() << "nArray after initialization:n" << integers3; Main
  • 7. // use overloaded assignment (=) operator cout << "nAssigning integers2 to integers1:" << endl; integers1 = integers2; // note target Array is smaller cout << "integers1:n" << integers1 << "integers2:n" << integers2; // use overloaded equality (==) operator cout << "nEvaluating: integers1 == integers2" << endl; if ( integers1 == integers2 ) cout << "integers1 and integers2 are equal" << endl; // use overloaded subscript operator to create rvalue cout << "nintegers1[5] is " << integers1[ 5 ]; Main
  • 8. // use overloaded subscript operator to create lvalue cout << "nnAssigning 1000 to integers1[5]" << endl; integers1[ 5 ] = 1000; cout << "integers1:n" << integers1; // attempt to use out-of-range subscript cout << "nAttempt to assign 1000 to integers1[15]" << endl; integers1[ 15 ] = 1000; // ERROR: out of range return 0; } // end main Main
  • 9. Array::Array( int arraySize ) { size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize ptr = new int[ size ]; // create space for pointer-based array for ( int i = 0; i < size; i++ ) ptr[ i ] = 0; // set pointer-based array element } // end Array default constructor // copy constructor for class Array; // must receive a reference to prevent infinite recursion Array::Array( const Array &arrayToCopy ) : size( arrayToCopy.size ) { ptr = new int[ size ]; // create space for pointer-based array for ( int i = 0; i < size; i++ ) ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object } // end Array copy constructor Array.cpp
  • 10. Array::Array( int arraySize ) { size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize ptr = new int[ size ]; // create space for pointer-based array for ( int i = 0; i < size; i++ ) ptr[ i ] = 0; // set pointer-based array element } // end Array default constructor // copy constructor for class Array; // must receive a reference to prevent infinite recursion Array::Array( const Array &arrayToCopy ) : size( arrayToCopy.size ) { ptr = new int[ size ]; // create space for pointer-based array for ( int i = 0; i < size; i++ ) ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object } // end Array copy constructor Array.cpp: Constructors
  • 11. // destructor for class Array Array::~Array() { delete [] ptr; // release pointer-based array space } // end destructor // return number of elements of Array int Array::getSize() const { return size; // number of elements in Array } // end function getSize Array.cpp: Destructor
  • 12. // overloaded assignment operator; // const return avoids: ( a1 = a2 ) = a3 const Array &Array::operator=( const Array &right ) { if ( &right != this ) // avoid self-assignment { // for Arrays of different sizes, deallocate original // left-side array, then allocate new left-side array if ( size != right.size ) { delete [] ptr; // release space size = right.size; // resize this object ptr = new int[ size ]; // create space for array copy } // end inner if for ( int i = 0; i < size; i++ ) ptr[ i ] = right.ptr[ i ]; // copy array into object } // end outer if return *this; // enables x = y = z, for example } // end function operator= Array.cpp: Assignment
  • 13. // determine if two Arrays are equal and // return true, otherwise return false bool Array::operator==( const Array &right ) const { if ( size != right.size ) return false; // arrays of different number of elements for ( int i = 0; i < size; i++ ) if ( ptr[ i ] != right.ptr[ i ] ) return false; // Array contents are not equal return true; // Arrays are equal } // end function operator== Array.cpp: Equality
  • 14. // overloaded subscript operator for non-const Arrays; // reference return creates a modifiable lvalue int &Array::operator[]( int subscript ) { // check for subscript out-of-range error if ( subscript < 0 || subscript >= size ) { cerr << "nError: Subscript " << subscript << " out of range" << endl; exit( 1 ); // terminate program; subscript out of range } // end if return ptr[ subscript ]; // reference return } // end function operator[] Array.cpp: Subscript
  • 15. // overloaded subscript operator for const Arrays // const reference return creates an rvalue int Array::operator[]( int subscript ) const { // check for subscript out-of-range error if ( subscript < 0 || subscript >= size ) { cerr << "nError: Subscript " << subscript << " out of range" << endl; exit( 1 ); // terminate program; subscript out of range } // end if return ptr[ subscript ]; // returns copy of this element } // end function operator[] Array.cpp: Subscript
  • 16. // overloaded output operator for class Array ostream &operator<<( ostream &output, const Array &a ) { int i; // output private ptr-based array for ( i = 0; i < a.size; i++ ) { output << setw( 12 ) << a.ptr[ i ]; if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output output << endl; } // end for if ( i % 4 != 0 ) // end last line of output output << endl; return output; // enables cout << x << y; } // end function operator<< Stream insertion
  • 17. // overloaded input operator for class Array; // inputs values for entire Array istream &operator>>( istream &input, Array &a ) { for ( int i = 0; i < a.size; i++ ) input >> a.ptr[ i ]; return input; // enables cin >> x >> y; } // end function Stream Extraction