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

PPTX
Synapse india dotnet development overloading operater part 3
TXT
PPT
OO JS for AS3 Devs
TXT
ODP
Javascript Unit Testing
PPTX
Command line arguments
PPTX
Variadic functions
PDF
PyCon lightning talk on my Toro module for Tornado
Synapse india dotnet development overloading operater part 3
OO JS for AS3 Devs
Javascript Unit Testing
Command line arguments
Variadic functions
PyCon lightning talk on my Toro module for Tornado

What's hot (20)

PDF
Advanced Patterns with io.ReadWriter
PPTX
Hive - ORIEN IT
PDF
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
PPT
Synapse india complain sharing info on chapter 8 operator overloading
PDF
Exploring ES6
PPTX
Namespaces
PPTX
Chapter iii(advance function)
PDF
Design patterns in javascript
PDF
R/C++ talk at earl 2014
PPT
From OCaml To Javascript At Skydeck
KEY
Python Yield
TXT
F sh3tdkeq
PPTX
Curso de Node.js e MongoDB - 16
PPTX
PHP in 2018 - Q1 - AFUP Limoges
PPT
Operator overloading
PPT
Computer notes - Reference Variables –II
PDF
__array_function__ conceptual design & related concepts
Advanced Patterns with io.ReadWriter
Hive - ORIEN IT
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Synapse india complain sharing info on chapter 8 operator overloading
Exploring ES6
Namespaces
Chapter iii(advance function)
Design patterns in javascript
R/C++ talk at earl 2014
From OCaml To Javascript At Skydeck
Python Yield
F sh3tdkeq
Curso de Node.js e MongoDB - 16
PHP in 2018 - Q1 - AFUP Limoges
Operator overloading
Computer notes - Reference Variables –II
__array_function__ conceptual design & related concepts
Ad

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

PPT
Operator overloading Object Oriented Programming
PPTX
Operator Overloading & Type Conversions
PPT
lecture12.ppt
PPT
Operator overloading in c++ is the most required.
PPT
OOP OOOOOverloading Concept lecture12.ppt
PPT
operator overloading concept in oops lecture12.ppt
PDF
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
PDF
template-typename T- class Array { public- ---------------------------.pdf
PDF
C++ L04-Array+String
PDF
C++ normal assignments by maharshi_jd.pdf
PDF
05_Arrays C plus Programming language22.pdf
DOC
Oops lab manual2
PDF
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
PPT
Lecture#9 Arrays in c++
PPT
Operator overloading
PPT
its arrays ppt for first year students .
PPT
lecture7.ppt
PPTX
week14Pointers_II. pointers pemrograman dasar C++.pptx
PDF
C++ practical
PPTX
Arrays matrix 2020 ab
Operator overloading Object Oriented Programming
Operator Overloading & Type Conversions
lecture12.ppt
Operator overloading in c++ is the most required.
OOP OOOOOverloading Concept lecture12.ppt
operator overloading concept in oops lecture12.ppt
#include -algorithm- #include -cstdlib- #include -iostream- #include -.pdf
template-typename T- class Array { public- ---------------------------.pdf
C++ L04-Array+String
C++ normal assignments by maharshi_jd.pdf
05_Arrays C plus Programming language22.pdf
Oops lab manual2
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
Lecture#9 Arrays in c++
Operator overloading
its arrays ppt for first year students .
lecture7.ppt
week14Pointers_II. pointers pemrograman dasar C++.pptx
C++ practical
Arrays matrix 2020 ab
Ad

More from Syed Zaid Irshad (20)

PDF
Data Structures & Algorithms - Spring 2025.pdf
PDF
Operating System.pdf
PDF
DBMS_Lab_Manual_&_Solution
PPTX
Data Structure and Algorithms.pptx
PPTX
Design and Analysis of Algorithms.pptx
PPTX
Professional Issues in Computing
PDF
Reduce course notes class xi
PDF
Reduce course notes class xii
PDF
Introduction to Database
PDF
C Language
PDF
Flowchart
PDF
Algorithm Pseudo
PDF
Computer Programming
PDF
ICS 2nd Year Book Introduction
PDF
Security, Copyright and the Law
PDF
Computer Architecture
PDF
Data Communication
PDF
Information Networks
PDF
Basic Concept of Information Technology
PDF
Introduction to ICS 1st Year Book
Data Structures & Algorithms - Spring 2025.pdf
Operating System.pdf
DBMS_Lab_Manual_&_Solution
Data Structure and Algorithms.pptx
Design and Analysis of Algorithms.pptx
Professional Issues in Computing
Reduce course notes class xi
Reduce course notes class xii
Introduction to Database
C Language
Flowchart
Algorithm Pseudo
Computer Programming
ICS 2nd Year Book Introduction
Security, Copyright and the Law
Computer Architecture
Data Communication
Information Networks
Basic Concept of Information Technology
Introduction to ICS 1st Year Book

Recently uploaded (20)

PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
OOP with Java - Java Introduction (Basics)
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Well-logging-methods_new................
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Digital Logic Computer Design lecture notes
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
PPT on Performance Review to get promotions
PPTX
Construction Project Organization Group 2.pptx
PDF
composite construction of structures.pdf
PDF
Structs to JSON How Go Powers REST APIs.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Arduino robotics embedded978-1-4302-3184-4.pdf
573137875-Attendance-Management-System-original
UNIT-1 - COAL BASED THERMAL POWER PLANTS
OOP with Java - Java Introduction (Basics)
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Well-logging-methods_new................
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Digital Logic Computer Design lecture notes
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT on Performance Review to get promotions
Construction Project Organization Group 2.pptx
composite construction of structures.pdf
Structs to JSON How Go Powers REST APIs.pdf

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