Working with Classes. A method dealing with two objects C++ has a pointer which call this. It gives the address of an object. Suppose we have two objects.

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Operator Overloading Fundamentals
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Function Overloading Having more than one function with the same name. list of argument of a function are called signature of a function. We can have more.
Working with Classes. A method dealing with two objects C++ has a pointer which call this. It gives the address of an object. Suppose we have two objects.
Chapter 14: Overloading and Templates
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
1 Classes and Objects Overview l Classes and Objects l Constructors l Implicit Constructors l Overloading methods this keyword l public, private and protected.
Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public:
1 Classes Separating interface from implementation Place the class declaration in a header file (.h) to be included (via #include) in each file that uses.
Operator Overloading 1. Introduction Let’s define a class for Complex numbers: class Complex { private: double real, image; public: Complex () : real(0.0),
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Operator Overloading Like most languages, C++ supports a set of operators for its built-in types. Example: int x=2+3; // x=5 However, most concepts for.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
1 CSC241: Object Oriented Programming Lecture No 05.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
CS410 – Software Engineering Lecture #12: C++ Basics V
Yan Shi CS/SE 2630 Lecture Notes
Programming Abstractions
Programming with ANSI C ++
Submission Example May 14, 2018
Lecture 3 John Woodward.
Inheritance CMSC 202, Version 4/02.
Visit for more Learning Resources
Object-Oriented Design (OOD) and C++
A First C++ Class – a Circle
Classes Object-oriented programming: Example: Bank transactions
Implementing Classes Yonglei Tao.
The dirty secrets of objects
Chapter Three - Implementing Classes
More on Classes Classes may have constructors which are called when objects are created and destructors which are called when objects are destroyed. Classes.
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Operator Overloading
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Abstraction: Generic Programming, pt. 2
Operator overloading Dr. Bhargavi Goswami
Review of Function Overloading
Operator overloading Friend Function This Operator Inline Function
Presentation transcript:

Working with Classes

A method dealing with two objects C++ has a pointer which call this. It gives the address of an object. Suppose we have two objects of BankAccount class and we want to know which one has more balance.

Solution : Have a method that returns a reference to the object with larger balance.

Header file for BankAccount class #ifndef BANK1_H #define BANK1_H class BankAccount { private : double balance; string name; public : BankAccount(); BankAccount(double initial_balance); void deposit (double amount); void withdraw (double amount ); double getBalance(); const BankAccount & topval( const BankAccount & s) const; ~BankAccount(); }; #endif

CPP file #include #include “bank1.h” BankAccount :: BankAccount() { balance = 0; } BankAccount :: BankAccount(double initialBalance, string str) { balance = initialBalance; name=str; }

void BankAccount ::deposit(double amount { balance =balance+amount ; } void BankAccount::withdraw(double amount) { if ( amount > balance ) amount=0; else balance=balance-amount; }

double BankAccount :: getBalance() { return balance; } BankAccount :: ~BankAccount() { cout<<“good bye”; }

const BankAccount & BankAccount :: topval( const BankAccount & s) const { if (s.balance > balance) return s; else return *this; } /* const in parenthesis says that the function won’t modify the explicitly accessed object */

/* the const after parenthesis says that the function won’t modify the implicitly accessed objects*/ The function returns a reference to one of the two const objects has to be constant. top=account1.topval(account2);

Operator Overloading Like function overloading we can have operator overloading. We have already used operator overloading we use * for multiplication and * for pointer. C++ allows user to overload operators.

Suppose we want to overload “+” to add two arrays. for(int i=0; i<20;i++) Array3[i]=Array1[i]+Array2[i]; // add element by element We can define a class that overload + so we can have Array3=Array1+Array2;

To overload an operator we use a special function call. operatorop(arguments-list); here op is a operator known for C++. For example: operator+(); // overload + // is not a C++ operator

#ifndef MYTIME0_H_ #define MYTIME0_H_ class Time { private: int hours; int minutes; public: Time(); Time(int h, int m); void AddMin(int m); void AddHr(int h); void Reset(int h, int m); Time Sum (const Time &t) const ; void Show(); }; #endif

#include #include “mytime0.h”; Time :: Time() { hours=minutes=0; } Time::Time(int h, int m) { hours=h; minutes=m; }

void Time::AddMin(int m) { minutes+=m; hours+=minutes/60; minutes %=60; } void Time::AddHr(int h) { hours+=h; }

void Time::Reset(int h, int m) { hours=h; minutes=m; } Time Time::Sum(const Time &t) const { Time sum; sum.minutes=minutes+t.minutes; sum.hours=hours+t.hours+sum.minutes/60; sum.minutes %=60; return sum; }

void Time:: Show() { cout<<hours<<“hours,” <<minutes<<“ minutes”; }

#include #include “mytime0.h”; int main() { Time coding(2,40); Time fixing(5,55); Time total; total=coding.Sum(fixing); total.Show(); return 0; }

#ifndef MYTIME0_H_ #define MYTIME0_H_ class Time { private: int hours; int minutes; public: Time(); Time(int h, int m); void AddMin(int m); void AddHr(int h); void Reset(int h, int m); Time operator+(const Time &t) const; Time operator *(double mult) const; void Show(); }; #endif

#include #include “mytime0.h”; Time :: Time() { hours=minutes=0; } Time::Time(int h, int m) { hours=h; minutes=m; }

void Time::AddMin(int m) { minutes+=m; hours+=minutes/60; minutes %=60; } void Time::AddHr(int h) { hours+=h; }

void Time::Rese(int h, int m) { hours=h; minutes=m; } Time Time::operator+(const Time &t) const { Time sum; sum.minutes=minutes+t.minutes; sum.hours=hours+t.hours+sum.minutes/60; sum.minutes %=60; return sum; }

Time Time::operator*(double mult) const { Time result; long totalmin=hours*mult*60+minutes*mult; result.hours=totalmin/60; result.minutes =totalmin % 60; return result; } void Time:: Show() { cout<<hours<<“hours,” <<minutes<<“ minutes”; }

#include #include “mytime0.h”; int main() { Time coding(2,40); Time fixing(5,55); Time total; total=coding+fixing; total.Show(); Time morefixing(3,28); total=morefixing.operator+(total); total.Show(); total=morefixing* 2.5; total.Show(); return 0; }

Time t1,t2,t3,t4; t4=t1+t2+t3; t4=t1.operator+(t2+t3); t4=t1. operator+(t2.operator+(t3));

Overloading Restriction Should preserve the syntax for the original operator. Time test, %test /// invalid We can’t create new operator symbols like operator **(); We can’t overload the following operators : sizeof. :: ?:

Operators can be overloaded + - * / % ^ > += -= ! = %= ^= &= |= << && -- () [ ] new -> delete

= Assignment () Function call [ ] Subscripting -> class member access by pointer Can be overloaded only by member function.

Friend Function When a function f is a friend of a class, f has the same access to class as a function member has. We could write : Time A,B; A=B*2.5 ; // A=B.operator*(2.5); But not A=2.5*B;

Creating a Friend function friend Time operator*( double m, const Time &t); Place it in the class declaration. Time operator*(double m, const Time &t) { Time result; long totalmin=t.hours*m*60+t.minutes*m; result.hours=totalmin/60; result.minutes =totalmin % 60; return result; }

A=2.5*B; Is A=operator*(2.5,B); Time operator*(double m, const Time &t) { return t*m; }

Overload << We want to have Time t; cout<<t; instead of t.Show(); both cout and t are objects. If we want to overload << with a member function then we should write t<<cout; //odd

Add friend void operator<<(ostream &os,const Time &t); Then the body : void operator<<(ostream &os,const Time &t) { os<<t.hours<<“ hours, “<<t.minutes<<“minutes”; }

Can we write cout<< “ time “ << t<< “ Tuesday \n”; ?? No “ Note that cout<<x; return an object cout of class ostream”; int x,y; cout<<x<<y; we have (cout<<x) <<y;

ostream & operator<<(ostream &os,const Time &t) { os<<t.hours<<“hours,“<<t.minutes<<“minutes”; return os; }

Type Casting for Classes When we write long count=8; double time=11; we have conversion automatically.

#ifndef STONEWT_H_ #define STONEWT_H_ class Stonewt { private: enum{lbs_per_stn=14}; int stone; double pds_left; double pounds; public: Stonewt(double lbs); Stonewt(int stn, doub lbs); Stonewt(); ~Stonewt(); void show_lbs() ; void show_stn(); }; #endif;

#include #include “stonewt.h”; Stonwt::Stonewt(double lbs) { stone=int(lbs) / lbs_per_stn; pds_left=int(lbs)%lbs_per_stn+lbs-int(lbs); pounds=lbs; } Stonewt::Stonewt(int stn, double lbs) { stone=stn; pds_left=lbs; pounds=stn*lbs_per_stn+lbs; }

Stonewt::Stonewt() { stone=0; pound=pds_left=0.0; } void Stonewt::show_stn() { cout<<stone<<“ stone,“ <<pds_left<<“ pounds\n”; } void Stonewt::show_lbs() { cout<<pounds<<“ pounds\n”; }

now we can write Stonewt mycat; mycat=19.6; this conversion automatically happen and is implicit conversion. // it can lead to unexpected conversion In order to make a conversion explicit we can write explicit Stonewt(double lbs);

Stonewt mycat; mycat=19.6 // is not valid mycat=Stonewt(19.6); Can we convert an object to double ? Yes, but not using constructors. We can use conversion function.

#ifndef STONEWT_H_ #define STONEWT_H_ class Stonewt { private: enum{lbs_per_stn=14}; int stone; double pds_left; double pounds; public: Stonewt(double lbs); Stonewt(int stn, double lbs); Stonewt(); ~Stonewt(); void show_lbs() ; void show_stn(); operator int() const; operator double() const; }; #endif;

Stonewt::operator int() const { return int (pounds+0.5); } Stonewt::operator double() const { return pounds; }

We can write : Stonewt poppins(9,2.8); double p_wt= poppins; //implicit cout<<p_wt<<endl; cout<<int( poppins);