Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 5-6 OOP Overview. Outline A Review of C++ Classes (Lecture 5) OOP, ADTs and Classes Class Definition, Implementation and Use Constructors and."— Presentation transcript:

1 Lecture 5-6 OOP Overview

2 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

3 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

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

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

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

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

8 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

9 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

10 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

11 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

12 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

13 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

14 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

15 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

16 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

17 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

18 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

19 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

20 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

21 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

22 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

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

24 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

25 A Quiz -1.0 0.8 0.3 -0.6 x -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp 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;...

26 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.

27 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp 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; };

28 point Implementation We will look at the body of intialize, which must assign its two arguments to the two private member variables. x -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp 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; };

29 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp void point::initialize(double init_x, double init_y) { x = init_x; y = init_y; }

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

31 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

32 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp If we activate p1.initialize: then p1.x and p1.y If we activate p2.initialize then p2.x and p2.y

33 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp double point::get_x() { return x; }

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

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

36 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

37 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

38 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp First improvement: automatic initialization without activating the initialize function

39 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

40 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp -function name same as class name - no return type, even no “void” !

41 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

42 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp

43 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

44 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp First improvement: automatic initialization without explicitly activating an initialize function

45 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp First improvement: automatic initialization without explicitly activating an initialize function

46 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp Can we want define an object with no parameters, not even a pair of parentheses?

47 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp Implementation point::point() { x = 0.0; y = 0.0; }

48 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?

49 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

50 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.

51 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();

52 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();

53 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

54 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

55 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

56 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

57 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);

58 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

59 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); … };

60 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!

61 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

62 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp formal parameter actual argument -1.5, -2.5 3 1.5, 0.5 ? -1.5, -2.5 3 -1.5, -2.5

63 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

64 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 -2 -1 0 1 2 -2 -1 0 1 2 2 1 0-2yp type_name & para_name NO & ! -1.5, -2.5 3 1.5, 0.5

65 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!

66 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.

67 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; }

68 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

69 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;

70 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)

71 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; }

72 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

73 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; }

74 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; }

75 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

76 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()); }

77 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); }

78 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 ;

79 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

80 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; }

81 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: … };

82 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; }

83 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

84 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 }

85 END


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

Similar presentations


Ads by Google