Lecture 5-6 OOP Overview. Outline A Review of C++ Classes (Lecture 5) OOP, ADTs and Classes Class Definition, Implementation and Use Constructors and.

Slides:



Advertisements
Similar presentations
 Chapter 2 introduces Object Oriented Programming.  OOP is a relatively new approach to programming which supports the creation of new data types and.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב ' Classes – - המשך.
Chapter 14: Overloading and Templates
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב' Classes.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Chapter 15: Operator Overloading
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
IT PUTS THE ++ IN C++ Object Oriented Programming.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
1 CSE 303 Lecture 22 Advanced Classes and Objects in C++ slides created by Marty Stepp
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Case Study - Fractions Timothy Budd Oregon State University.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Zhigang Zhu Department of Computer Science.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Xiaoyan Li CSC211 Data Structures Lecture 2 ADT and C++ Classes (I) Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 2 ADT and C++ Classes (I) Instructor: Zhigang Zhu Department of Computer Science City.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
 Chapter 2 introduces Object Oriented Programming.  OOP is a relatively new approach to programming which supports the creation of new data types and.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Classes in C++ By: Mr. Jacobs. Objectives  Explore the implications of permitting programmers to define their own data types and then present C++ mechanism.
Object Oriented Programming Data Structures and Other Objects Using C++ Dr. Donghyun Kim Department of Computer Science College of Computing and Software.
Chapter 12 Classes and Abstraction
Structures and Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Object Oriented Programming
CSC212 Data Structure - Section BC
A First C++ Class – a Circle
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CSC212 Data Structure - Section EF
6 Chapter Functions.
Defining Classes and Methods
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Lecture 5-6 OOP Overview

Outline A Review of C++ Classes (Lecture 5) OOP, ADTs and Classes Class Definition, Implementation and Use Constructors and Value Semantics More on Classes (Lecture 6) Classes and Parameters Operator Overloading Namespaces

C++ Classes and ADTs Class –Mechanism to create objects and member functions –Support information hiding Abstract Date Types (ADTs) –Class as an ADT that programmers can use without knowing how the member functions are implemented - i.e. with information hiding

A point ADT A data type to store and manipulate a single point on a plane Manipulations –Initialize –Retrieval –Shift x yp1

A point ADT A data type to store and manipulate a single point on a plane Manipulations –Initialize –Retrieval coordinates –Shift x yp1 (-1, 0.8)

A point ADT A data type to store and manipulate a single point on a plane Manipulations –Initialize –Retrieval coordinates –Shift x y0.8 p1

A point ADT A data type to store and manipulate a single point on a plane Manipulations –Initialize –Retrieval coordinates –Shift by x y (0.3, -0.6) (1.3, -1.4) (1.3, -1.4) p2 p1

point Definition We can implement the point object using a data type called a class. class point {... }; Don’t forget the semicolon at the end x yp

point Definition The class will have two components called x and y. These components are the x and y coordinates of this point. Using a class permits two new features... class point {... double x; double y; }; x yp

point Definition ÊThe two components will be private member variables. This ensures that nobody can directly access this information. The only access is through functions that we provide for the class. class point {... private: double x; double y; }; x yp

point Definition ËIn a class, the functions which manipulate the class are also listed. class point { public:... private: double x; double y; }; Prototypes for the point member functions go here, after the word public: x yp

point Definition class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x() const; double get_y( ) const; private: double x; double y; }; Our point has at least four member functions: Function bodies will be elsewhere. x yp

point Definition class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x( ) const; double get_y( ) const; private: double x; double y; }; The keyword const appears after two prototypes: This means that these functions will not change the data stored in a point ADT. x yp

Files for the point ADT The point class definition, which we have just seen, is placed with documentation in a file called point.h, outlined here. The implementations of the four member functions will be placed in a separate file called point.cpp, which we will examine in a few minutes. But first, we will see an example program that users points. Documentation: (Preconditions and Postconditions) Class definition: point class definition which we have already seen x yp

Using the point ADT A program that wants to use the point ADT must include the point.h header file (along with its other header inclusions). File pointmain1.cpp #include #include “point.h"... x yp

Using the point ADT Just for illustration, the example program will declare two point objects named p1 and p2. #include #include “point.h" int main( ) { point p1; point p2; x yp

Using the point ADT The program starts by activating the initialize member function for p1. #include #include “point.h" int main( ) { point p1: point p2; p1. initialize(-1.0, 0.8); x yp

Using the point ADT ÊThe member function activation consists of four parts, starting with the object name. int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); Name of the object x yp

Using the point ADT ËThe instance (object) name is followed by a period. int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); A Period x yp

Using the point ADT ÌAfter the period is the name of the member function that you are activating. int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); Name of the Function x yp

Using the point ADT ÍFinally, the arguments for the member function. In this example the first argument (x coordinate) and the second argument (y coordinate) #include "thinker.h" int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); Arguments x yp

A Quiz How would you activate p1's get_x member function ? What would be the output of p1's get_x member function at this point in the program ? int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); x yp

A Quiz Notice that the get_x member function has no arguments. At this point, activating p1.get_x will return a double value int main( ) { point p1; point p2; p1. initialize(-1.0, 0.8); cout << p1. get_x( ) <<endl; x yp

A Quiz Trace through this program, and tell me the complete output. int main( ) { point p1; point p2; p1.initialize(-1.0, 0.8); cout << p1.get_x( ) << p1.get_y() << endl; p2.initialize(p1.get_x(), p1.get_y()); cout << p2.get_x( ) << p2.get_y() << endl; p2.shift(1.3, -1.4); cout << p2.get_x( ) << p2.get_y() << endl;... x yp

A Quiz x yp int main( ) { point p1; point p2; p1.initialize(-1.0, 0.8); cout << p1.get_x( ) << p1.get_y() << endl; p2.initialize(p1.get_x(), p1.get_y()); cout << p2.get_x( ) << p2.get_y() << endl; p2.shift(1.3, -1.4); cout << p2.get_x( ) << p2.get_y() << endl;...

What you know about Objects 4 Class = Data + Member Functions. 4 You know how to define a new class type, and place the definition in a header file. 4 You know how to use the header file in a program which declares instances of the class type. 4 You know how to activate member functions. 6But you still need to learn how to write the bodies of a class’s member functions.

point Implementation Remember that the member function’s bodies generally appear in a separate point.cpp file. Function bodies will be in.cpp file. Function bodies will be in.cpp file. x yp class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x( ) const; double get_y( ) const; private: double x; double y; };

point Implementation We will look at the body of intialize, which must assign its two arguments to the two private member variables. x yp class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x( ) const; double get_y( ) const; private: double x; double y; };

point Implementation ÊNote that in the heading, the function's name is preceded by the class name and :: - otherwise C++ won't realize this is a class’s member function. x yp void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; }

point Implementation ËWithin the body of the function, the class’s member variables and other member functions may all be accessed. x yp void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; }

void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; } point Implementation ËWithin the body of the function, the class’s member variables and other member functions may all be accessed. But, whose member variables are these? Are they p1.x and p1.y or p2.x and p2.y ? x yp

void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; } point Implementation ËWithin the body of the function, the class’s member variables and other member functions may all be accessed. x yp If we activate p1.initialize: then p1.x and p1.y If we activate p2.initialize then p2.x and p2.y

point Implementation Here is the implementation of the get_x member function, which return the x coordinate: Notice how this member function implementation uses the member variable x of the point object. x yp double point::get_x() { return x; }

point Implementation Member functions may activate other member functions Notice this member function implementation still directly assign the member variables x and y. x yp void point::origin() { x = 0.0; y = 0.0; }

point Implementation Member functions may activate other member functions Notice how this member function implementation uses the member function initialize. x yp void point::origin() { initialize(0.0, 0.0); } Without object name

class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x( ) const; double get_y( ) const; private: double x; double y; }; A Common Pattern Often, one or more member functions will place data in the member variables... p...so that other member functions may use that data. Initialize & shift get_x & get_y

Classes have member variables and member functions. An object is a variable where the data type is a class. You should know how to declare a new class type, how to implement its member functions, how to use the class type. Frequently, the member functions of an class type place information in the member variables, or use information that's already in the member variables. Next we will see more features of OOP and classes. Summary of classes

Constructors: point Initialization The program starts by activating the initialize member function for p1. #include #include “point.h" int main( ) { point p1: point p2; p1. initialize(-1.0, 0.8); x yp First improvement: automatic initialization without activating the initialize function

Constructors: point Initialization class point { public: void initialize(double init_x, double init_y); void shift(double dx, double dy); double get_x() const; double get_y( ) const; private: double x; double y; }; We can provide a normal member function initialize x yp

Constructors: point Initialization class point { public: point(double init_x, double init_y); void shift(double dx, double dy); double get_x() const; double get_y( ) const; private: double x; double y; }; Or use a constructor that is automatically called x yp -function name same as class name - no return type, even no “void” !

Constructors: Implementation void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; } For the most part, the constructor is no different than any other member functions. We only need to replace initialize with point x yp

Constructors: Implementation point::point(double init_x, double init_y) { x = init_x; y = init_y; } For the most part, the constructor is no different than any other member functions. But there are some special features about constructor... x yp

Constructors Constructor is a member function which – the name must be the same as the class name – automatically called whenever a variable of the class is declared – arguments must be given after the variable name (when declared in user file) A way to improve the initialize function – by providing an initialization function that is guaranteed to be called

Constructors: point Initialization Automatically called when declared. Parameters after the object names #include #include “point.h" int main( ) { point p1: point p2; p1. initialize(-1.0, 0.8); x yp First improvement: automatic initialization without explicitly activating an initialize function

Constructors: point Initialization Automatically called when declared. Parameters after the object names #include #include “point.h" int main( ) { point p1(-1.0, 0.8): point p2(0.3, 0.6); x yp First improvement: automatic initialization without explicitly activating an initialize function

Default Constructors Automatically called when declared. Parameters after the object names NO parameters after the object name p2 #include #include “point.h" int main( ) { point p1(-1.0, 0.8); point p2; x yp Can we want define an object with no parameters, not even a pair of parentheses?

Default Constructors class point { public: point(); point(double init_x, double init_y); … private: double x; double y; }; We could provide a second constructor with no parameters x yp Implementation point::point() { x = 0.0; y = 0.0; }

Constructors: Function Overloading You may declare as many constructors as you like – one for each different way of initializing an object Each constructor must have a distinct parameter list so that the compiler can tell them part Question: How many default constructors are allowed?

Constructors: automatic default constructor What happens if you write a class without any constructors? The compiler automatically creates a simple default constructor – which only calls the default constructors for the member variables that are objects of some other classes Programming Tip :Always provide your own constructors, and better with a default constructor

Value Semantics of a Class Value semantics determines how values are copied from one object to another Consists of two operations in C++ – The assignment operator – The copy constructor Document the value semantics –When you implement an ADT, include a comment indicating what the value semantics is used.

Value Semantics: assignment operator Automatic assignment operator – For a new class, C++ normally carries out assignment by simply copying each variable from the object on the right to that on the left –Our new class point can use automatic assignment operator point p1(-1.0, 0.8), p2; p2 = p1; cout << p2.get_x() <<“ “ << p2.get_y();

Value Semantics: copy constructor A copy constructor –is a constructor with one parameter whose data type is the same as the constructor’s class –initializes a new object as an exact copy of an existing object Examples: point p1(-1.0, 0.8); point p2 (p1); cout << p2.get_x() <<“ “ << p2.get_y(); point p1(-1.0, 0.8); point p2 = p1; cout << p2.get_x() <<“ “<< p2.get_y();

point p2 = p1; versus p2 = p1; – The assignment p2 = p1; merely copies p1 to the already existing object p2 using the assignment operator. –The syntax point p2 = p1; looks like an assignment statement, but actually a declaration that both declares a new object, and calls the copy constructor to initialize p2 as a copy of p1. p2 will be the same if the assignment operator and the copy constructor do the same things Value Semantics: discussion

Constructors, etc.– a summary Constructor is a member function – define your own constructors (including a default) – automatic default constructor Value semantics of a class – assignment operators and copy constructor – automatic assignment op and copy constructor

Outline A Review of C++ Classes (Lecture 5) OOP, ADTs and Classes Class Definition, Implementation and Use Constructors and Value Semantics More on Classes (Lecture 6) Classes and Parameters Operator Overloading Namespaces

Default arguments A default argument is a value that will be used for an argument –When a programmer does not provide an actual argument when calling a function Default arguments may be listed in the prototype of a function – Syntax: Type_name var_name = default_value

Default arguments – rules The default argument is only specified once – in the prototype – not in the implementation No need to specify all the arguments as default but the default must be rightmost in the parameter list In a call, arguments with default may be omitted from the right end. Example of a prototype: int date_check (int year, int month = 1, int date =1); int date_check (int year, int month = 1, int date =1);

Default arguments – Examples Prototype: int date_check (int year, int month = 1, int date =1); int date_check (int year, int month = 1, int date =1); Usage in the calling function date_check(2002); // uses default for both month and date date_check(2002, 9); // uses default for date =1 date_check(2002, 9, 5); // does not use defaults

Default Constructor revisited A default constructor can be provided by using default arguments Instead of defining two constructors, we can define just one constructor with default arguments for all of its arguments class point { public: point(double init_x=0.0, double init_y =0.0); … };

Default Constructor revisited In using the class, we can have three declarations The implementation of the constructor with default arguments is the same as the usual one... point a(-1, 0.8); // uses the usual constructor with // two arguments point b(-1); // uses –1 for the first, // but use default for the second point c; // uses default arguments for both; // default constructor: // no arguments, no parentheses!

Class as type of parameter A class can be used as a function parameter, just like any other data type –Value parameters –Reference parameters –Const reference parameters –In fact you can also have const value parameters, even if this does not make many senses

Value parameters How many shifts to move p into the first quad Function implementation: int shifts_needed(point p) { int answer = 0; while ((p.get_x() <0) || (p.get_y()<0)) { p.shift(1,1); answer++; } return answer; } Calling program: point a(-1.5,-2.5); cout << a.get_x() << a.get_y() << endl; cout << shifts_needed(a) << endl; cout << a.get_x() << a.get_y() << endl; x yp formal parameter actual argument -1.5, , 0.5 ? -1.5, , -2.5

Value parameters A value parameter is declared by writing – type-name parameter-name Any change made to the formal parameter within the body of the function does not change the actual argument from the calling program The formal parameter is implemented as a local variable of the function and the copy constructor is used to initialize the formal parameter as a copy of the actual argument

Reference parameters Actually move p into the first quadrant Function implementation (almost the same except &): int shift_to_1st_quad(point& p) { int shifts; while ((p.get_x() <0) || (p.get_y()<0)) { p.shift(1,1); shifts++; } return shifts; } In calling program: point a(-1.5,-2.5); cout << a.get_x() << a.get_y() << endl; cout << shift_to_1st_quad(a) << endl; cout << a.get_x() << a.get_y() << endl; x yp type_name & para_name NO & ! -1.5, , 0.5

Reference parameters A reference parameter is declared by writing – type-name& parameter-name Any use of the formal parameter within the body of the function will access the actual argument from the calling program; change made to the parameter in the body of the function will alter the argument The formal parameter is merely another name of the argument used in the body of the function!

const reference parameters A const reference parameter is declared by writing – const type-name& parameter-name A solution that provides the efficiency of a reference parameter along with the security of a value parameter.

Class as return value point middle(const point& p1, const point& p2) { double x_midpoint, y_midpoint; // Compute the x and y midpoints x_midpoint = (p1.get_x( ) + p2.get_x( )) / 2; y_midpoint = (p1.get_y( ) + p2.get_y( )) / 2; // Construct a new point and return it point midpoint(x_midpoint, y_midpoint); return midpoint; }

Class as return value The type of a function’s return value may be a class Often the return value will be stored in a local variable of the function (such as midpoint ) –not always (could be in a formal parameter) C++ return statement uses the copy constructor to copy the function’s return value to a temporary location before returning the value to the calling program

Operator Overloading Question: –Can we perform arithmetic (+ - * /), comparison (> == <) or assignment operation (=) with a new class? Answer is NO – Unless we define a function that tells exactly what “!=” or “+” means point speed1(5,7) point speed2(1,2); point difference; if (speed1 != speed2 ) difference = speed1 - speed2;

Operator Overloading Binary Function –A function with two arguments Binary Operator –A operator with two operands p = p1 + p2; p = p1 + p2; p = add( p1, p2); p = add( p1, p2); Operator Overloading is defining the meaning of an existing operator for a new class Instead of defining point add(point p1, point p2) We define point operator+(point p1, point p2)

Overloading arithmetic operators point operator+(const point& p1, const point& p2) //Postcondition: the sum of p1 and p2 is returned. { double x_sum, y_sum; x_sum = (p1.get_x() + p2.get_x()); y_sum = (p1.get_y() + p2.get_y()); point sum(x_sum, y_sum); return sum; }

Overloading arithmetic operators Apart from the peculiar name operator+, the function is just like any other function The overloaded operator + is used in a program just like any other use of + –p = p1+ p2; When you overload an operator +, the usual usage of + is still available Note the uses of –const reference parameters –member functions get_x and get_y instead of variables

Overloading arithmetic operators Method 1: Nonmember function p = p1+p2 point operator+(const point& p1, const point& p2) //Postcondition: the sum of p1 and p2 is returned. { double x_sum, y_sum; x_sum = (p1.get_x() + p2.get_x()); y_sum = (p1.get_y() + p2.get_y()); point sum(x_sum, y_sum); return sum; }

Overloading arithmetic operators Method 2: Member function p = p1+p2 point point::operator+(const point& p2) const //Postcondition: the sum of activating object (p1) and argument p2 is returned. { double x_sum, y_sum; x_sum = (x + p2.get_x()); y_sum = (y + p2.get_y()); point sum(x_sum, y_sum); return sum; }

Overloading arithmetic operators Overloading using nonmember function –PROs: two arguments on equal footing –CONs: cannot use the member variables Overloading using member function –PROs: can use member variables –CONs: p1 activates the operator with argument p2

Overloading comparison operators bool operator==(const point& p1, const point& p2) //Postcondition: the return is true if p1 and p2 are identical; otherwise return is false. { return (p1.get_x() == p2.get_x()) && (p1.get_y() == p2.get_y()); }

Overloading comparison operators bool operator!=(const point& p1, const point& p2) //Postcondition: the return is true if p1 and p2 are NOT identical; otherwise return is false. { return (p1.get_x() != p2.get_x()) || (p1.get_y() != p2.get_y()); //or return !(p1== p2); }

Overloading I/O operators Input (>>) & Output (<<) for a new class: << Q1: how to use this overloaded operator? ostream& operator<<(ostream& outs, const point& source) // Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs. // Library facilities used: iostream { outs << source.get_x( ) << ", " << source.get_y( ); return outs; } cout << p ; cout << p ;

Overloading I/O operators Input (>>) & Output (<<) for a new class: << Q2: why is outs a reference parameter but NOT const? ostream& operator<<(ostream& outs, const point& source) // Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs. // Library facilities used: iostream { outs << source.get_x( ) << " " << source.get_y( ); return outs; } Need change actual argument cout

Overloading I/O operators How to overload the input operator >> ? Input (>>) & Output ( > NO const for both istream and point Problem: send input directly to private members! istream& operator>>(istream& ins, point& target) // Postcondition: The x and y coordinates of target have been // read from ins. The return value is the istream ins. // Library facilities used: iostream { ins >> target. x >> target.y; return ins; }

Friend Function Solution: use a member function for overloading the input function A friend function is NOT a class member, but it has access to its private members class point { public: … … // FRIEND FUNCTION friend istream& operator>>(istream& ins, point& target); private: … };

Overloading I/O operators No change in the implementation However it is a good practice to put a comment istream& operator>>(istream& ins, point& target) // Postcondition: The x and y coordinates of target have been // read from ins. The return value is the istream ins. // Library facilities used: iostream // Friend of point class { ins >> target. x >> target.y; return ins; }

Namespace and Documentation Goal: –to make our new point class easily available to any programs any time without revealing all the details worrying about name conflicts Three steps to fulfill the goal – Creating a namespace – Writing the header file – Writing the implementation file

Namespace Question: –You may use two versions of point in the same program Solution is to use the namespace technique –A namespace is a name that a programmer selects to identify a portion of his work –The name should be descriptive, you can include parts of your name and other features for uniqueness Three ways to use the items in a namespace –using namespace etgar_point_namespace; –using etgar_point_namespace ::point; –etgar_point_namespace ::point p1; Namespace etgar_point_namespace { // any item that belong to the namespace is written here }

END