תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב ' Classes – - המשך.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Chapter 14: Overloading and Templates
1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Lecture 5-6 OOP Overview. Outline A Review of C++ Classes (Lecture 5) OOP, ADTs and Classes Class Definition, Implementation and Use Constructors and.
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב' Classes.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Definition Class In C++, the class is the construct primarily used to create objects.
1 CSE 303 Lecture 22 Advanced Classes and Objects in C++ slides created by Marty Stepp
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
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
P Improvements - Constructor p Parameter passing Constructors Problem Solving With C++
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.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Object Oriented Programming (OOP) Lecture No. 8. Review ► Class  Concept  Definition ► Data members ► Member Functions ► Access specifier.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Zhigang Zhu Department of Computer Science.
1 CSC241: Object Oriented Programming Lecture No 02.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
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?
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
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.
February 28, 2005 Introduction to Classes. Object Oriented Programming An object is a software bundle of related variables and methods. Software objects.
1 CSC241: Object Oriented Programming Lecture No 03.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Constructors Initializing New Objects #include “fraction.h” int main() { float x; float y = 6.7; float z(7.2); Fraction.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 COMS 261 Computer Science I Title: Classes Date: November 4, 2005 Lecture Number: 27.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
6/24/2016Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 8 An Introduction.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Chapter 2 Objects and Classes
User-Written Functions
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?
C++ Programming Functions
Programming with ANSI C ++
CSC212 Data Structure - Section BC
Object-Oriented Programming (OOP) Lecture No. 21
C++ Programming Functions
System Programming Practical Session 8 C++ classes.
CS212: Object Oriented Analysis and Design
CSC212 Data Structure - Section EF
Dr. R Z Khan Handout-3 Classes
Templates CMSC 202, Version 4/02.
Presentation transcript:

תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב ' 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

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!

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

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

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

סיכום – מה ראינו עד עכשיו? הגדרת class – data & member functions מימוש ה -member functions הגדרת constructors ( בנאים ) –C ’ tor שמקבל פרמטרים –Default c ’ tor Copy c ’ tor – מתי נקרא ? כש -class מועבר כפרמטר לפונקציה by value כש -class מוחזר מפונקציה by value – כיצד מממשים copy c ’ tor הזכרנו את אופרטור ההשמה = להעתקה בין מחלקות אך עדיין לא ראינו איך מגדירים אותו