1 159.234 Lecture 14 Today: Overloading: Revision on this Revision on increment operators the assignment operator the [] operator Book: p.209-212, 215,

Slides:



Advertisements
Similar presentations
Complete Structure class Date {class Date { private :private : // private data and functions// private data and functions public :public : // public data.
Advertisements

Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Operator overloading redefine the operations of operators
BBIT 212/ CISY 111 Object Oriented Programming (OOP) Objects and classes, object interactions in Java
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Chapter 14 Inheritance Pages ( ) 1. Inheritance: ☼ Inheritance and composition are meaningful ways to relate two or more classes. ☼ Inheritance.
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Write a function to calculate the cubic function: y = 4x 3 + 2x 2 –5x – 4 The function should return y for any given value of x. Question One #include.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne
Derived data types Dealing with data –Where the information is stored –What value is kept there –What kind of information is stored Address operator Pointers.
1 CSC241: Object Oriented Programming Lecture No 21.
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
Exercise 2.
Data Structures (Second Part) Lecture 2 : Pointers Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Revision.
Operator Overloading. C++ 2 Outline  General technique  Overloading of the assignment operator  Overloading the increment and decrement operators.
Introduction to Programming Lecture 39. Copy Constructor.
第三次小考. #include using namespace std; int aaa(int *ib,int a1,int a2) { int u,v; int m=(a1+a2)/2; if(a1==a2)return ib[a1]; u=aaa(ib,a1,m); cout
Chapter 8. Operator Overloading Operator overloading gives the opportunity to redefine C++ Operator overloading refers to redefine C++ operators such.
EC-241 Object-Oriented Programming
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Derived Classes. C++ 2 Outline  Definition  Virtual functions  Virtual base classes  Abstract classes. Pure virtual functions.
Operator Overloading Fundamentals
C++ Classes & Data Abstraction
Tinaliah, S. Kom.. * * * * * * * * * * * * * * * * * #include using namespace std; void main () { for (int i = 1; i
Approfondimento Classi - Esempi1 // Argomento: Oggetti membri di altre classi // Declaration of the Date class. // Member functions defined in date1.cpp.
Triana Elizabeth, S.Kom. #include using namespace std; void main () { for (int i = 1; i
Esempio Polimorfismo1 // Definition of abstract base class Shape #ifndef SHAPE_H #define SHAPE_H class Shape { public: virtual double area() const { return.
OBJECT ORIENTED PROGRAMMING Instructor: Rashi Garg Coordinator: Gaurav Saxena.
1 Lab Session-4 CSIT121 Fall 2004 Scope of Variables Top Down Design Problem The Solution Lab Exercise for Demo.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Inheritance #1 First questions Similar to Python? What about visibility and encapsulation? – can an object of the child class access private members.
Static Keyword. What is static The static keyword is used when a member variable of a class has to be shared between all the instances of the class. All.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
Tracing through E01, question 9 – step 1 // p02.cc P. Conrad, for CISC181 07S // Exam question for E01 #include using namespace std; void mysteryFunction(int.
Objective: Students will be able to: Declare and use variables Input integers.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
February 28, 2005 Introduction to Classes. Object Oriented Programming An object is a software bundle of related variables and methods. Software objects.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
1 COMS 261 Computer Science I Title: Classes Date: November 4, 2005 Lecture Number: 27.
Classes Sujana Jyothi C++ Workshop Day 2. A class in C++ is an encapsulation of data members and functions that manipulate the data. A class is a mechanism.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Overloading Unary Operators
Examples of Classes & Objects
using System; namespace Demo01 { class Program
group work #hifiTeam
Polymorphism Lec
Static Data Member and Functions
Dynamic Memory Allocation Reference Variables
CSC 253 Lecture 8.
CSC 253 Lecture 8.
Contents Introduction to Constructor Characteristics of Constructor
Classes Short Review of Topics already covered Constructor
Assignment 7 User Defined Classes Part 2
JAVA Constructors.
Operator Overloading.
class PrintOnetoTen { public static void main(String args[]) {
List Iterator Implementation
Lab – 2018/04/12 implement getTotalCount to return how many ‘nMatrix’s are allocated(exist) (modify constructor and destructor, use static variable and.
CS31 Discussion 1D Winter18: week 6
Introduction to Algorithms and Programming COMP151
Chapter 11 Classes.
Presentation transcript:

Lecture 14 Today: Overloading: Revision on this Revision on increment operators the assignment operator the [] operator Book: p , 215,

2 #include using namespace std; class XClass{ // a conhtrive d example to illustrate use of this public: XClass(int id = 0) : ID(id) { // single arg constructor } XClass( int a, int b ){ // two arg constructor int tmp = a + b; this->common( tmp ); // not needed system does this-> automatically // same as just common(tmp); } void print(){ // "this" is automatically declared by the system for use in non static member functions cout << "this inside XClasses print member function is " << this << endl; XClass *ptr; ptr = this; // "this" is a pointer to the instantiated object // of which function print is a member XClass anotherXClass; anotherXClass = *this; } int getID(){ return this->ID; } // not needed - system does this-> automatically private: void common( int t ){ / a private member function only used by other members ID = t; } int ID; // some private data }; int main(){ XClass x1(90); // constructs an object XClass *xp; // declares a pointer xp = & x1; // xp now points at the x1 object cout << "ID of x1 is " << x1.getID() << endl; cout << "Address of x1 inside main is " << &x1 << endl; x1.print(); // invokes the print member function of x1 cout << "size of x1 is " << sizeof( x1 ) << endl; return 0; } Example Output: ID of x1 is 90 Address of x1 inside main is 0xbffffc68 this inside XClasses print member function is 0xbffffc68 size of x1 is 4 this is just a pointer to the instantiated object that is available inside non- static member functions of the object itself.

3 #include using namespace std; class Complex{ friend Complex operator+( const Complex & c1, const Complex & c2 ); friend ostream &operator<<( ostream & out, const Complex & c1 ); public: Complex( double real=0.0, double imag=0.0) : re(real), im(imag){} ~Complex(){} // empty destructor Complex( Complex const & c ){ // copy constructor re = c.re; im = c.im; } const Complex & operator=( const Complex & c ){ // assignment operator re = c.re; im = c.im; return *this; } void print( ostream & out ) const{ // utility used by output operator out << re << "," << im; } double abs(){ return sqrt( re * re + im * im ); } double Re(){ return re; } double Im(){ return im; } private: double re; double im; }; // addition operator definition for Complex operands Complex operator+( const Complex & c1, const Complex & c2 ){ Complex result( c1 ); result.re += c2.re; result.im += c2.im; return result; } // insertion stream operator, need not be a friend function if it does not access // private data directly ostream &operator<<( ostream & out, const Complex & c1 ){ //out << c1.re << "," << c1.im; c1.print( out ); return out; } int main(){ // test program for Complex class Complex a(1.0, 0.0); Complex b(0.0, 1.0); Complex c(-1.0); // im part will default to 0 Complex d(0.0); // im part will default to 0 Complex x; x = a + b; // this iswhat we want to work (needs + operator) //cout << x.re << "," << x.im << endl; // Illegal, data is private x.print( cout ); // should be 1,1 cout << endl; cout << c << endl; // this is what we want to work (needs output op) Complex y(0.0,0.0); x = y; // 2.0 as a double is automatically promoted to a Complex cout << x << endl; // should be 2,0 Complex c1, c2, c3, c4; c1 = c2 = c3 = c4 = x; // this is what we want to work (needs assignment op) cout << c1 << endl; // should be identical to x - ie 2,0 cout << c2 << endl; // also 2,0 return 0; } Output: 1,1 -1,0 2,0

4 Whenever we perform an assignment to an object, the class's assignment operator is invoked. Vect a, b, c, d; //… a = b; b = c = d; //multiple assignments The assignment operator must be a member function. Overloading the assignment operator

5 The Assignment Operator class Vect { // an elastic array public: Vect(int n); //n=size of the vector ( or array) ~Vect() {delete [] p;} const Vect &operator=(const Vect & v); private: int *p; int size; };

6 The Assignment Operator const Vect& Vect::operator=(const Vect &v){ if(this != &v) { //do nothing if assign to self delete[] p; p = new int[size=v.size]; assert(p); for (int i = 0;i<size;++i) p[i]=v.p[i]; } return *this; //return a copy of the object }

7 The Assignment Operator Always returns a const reference to the object being assigned. const Vect & operator=(const Vect & v); Why? a) it allows, several assignments to be chained together: Complex w, x, y, z; w = x = y = z = Complex(0,0); b) it is more efficient (a copy of the returned object does not have to be created and returned).

8 Other Assignment Operators If your application overloads the assignment operator, then the other forms of assignment (e.g., '+=', '-=', '/=', '*=',...) should be overloaded (for consistency make them member functions) just like the assignment operator.

9 The [] can be used on both sides of an assignment statement. Vect a(5); a[1] = 4; a[2] = a[1] * 3; Make sure to return a reference so that it may appear on the left-hand side of an assignment. It must be implemented as a member function. Overloading the [ ] Operator

10 Overloading the [] Operator We can create an array class that overloads [], and checks arrays bounds: class Vect { public: Vect(int n); ~Vect() {delete [] p;} int & operator[](cons int i); private: int *p; int size; };

11 Overloading the [] Operator Vect::Vect(int n) : size(n) { p = new int[size]; assert(p!=0); } int & Vect::operator[](const int i) { assert((i >= 0) && (i < size)); return p[i]; }

12 Summary Operator overloading uses: member functions, friend functions or non member functions. We have seen examples of overloading pre/postfix increment, binary (+, +=,…) > extraction and, =, []

13 ACM Student Magazine