! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Similar documents
! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

Procedural Programming

Introduction to Classes

Chapter 9 Classes : A Deeper Look, Part 1

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

A Deeper Look at Classes

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Computer Programming with C++ (21)

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Overloading Operators

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Abstraction in Software Development

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Classes: A Deeper Look

Introduction to Programming session 24

Fundamentals of Programming Session 24

System Design and Programming II

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming

C++ Classes, Constructor & Object Oriented Programming

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

57:017, Computers in Engineering C++ Classes

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Lecture #1. Introduction to Classes and Objects

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

III. Classes (Chap. 3)

IS 0020 Program Design and Software Tools

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Functions, Arrays & Structs

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Chapter 6: Classes and Data Abstraction

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Classes: A Deeper Look. Systems Programming

Recharge (int, int, int); //constructor declared void disply();

Functions, Arrays & Structs

2. It is possible for a structure variable to be a member of another structure variable.

by Pearson Education, Inc. All Rights Reserved. 2

Object Oriented Design

Lecture 7. Log into Linux New documents posted to course webpage

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Introduction Of Classes ( OOPS )

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Chapter 10 Introduction to Classes

Cpt S 122 Data Structures. Introduction to C++ Part II

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Object Oriented Design

CS304 Object Oriented Programming Final Term

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

CS24 Week 3 Lecture 1

Operator Overloading

IS 0020 Program Design and Software Tools

More C++ Classes. Systems Programming

Chapter 15: Object Oriented Programming

Chapter 15 - C++ As A "Better C"

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

EL2310 Scientific Programming

Constructor - example

Fast Introduction to Object Oriented Programming and C++

Data Structures using OOP C++ Lecture 3

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Chapter 16: Classes and Data Abstraction

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

G52CPP C++ Programming Lecture 9

Methods and Data (Savitch, Chapter 5)

IS 0020 Program Design and Software Tools

CS 247: Software Engineering Principles. ADT Design

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Object-Based Programming (Deitel chapter 8)

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Classes and Data Abstraction. Topic 5

Methods. Methods. Mysteries Revealed

EL2310 Scientific Programming

Object Oriented Design

CS3157: Advanced Programming. Outline

Implementing an ADT with a Class

CPSC 427: Object-Oriented Programming

Chapter 17 - C++ Classes: Part II

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Chapter 4. Defining Classes I

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS

Transcription:

Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform operations over the variables - Good example: movie inventory program! Usually variables are passed to the functions as arguments Focus is on organizing and implementing the functions. 1 2 Procedural Programming: Problem! It is not uncommon for - program specifications to change - representations of data to be changed for internal improvements.! As procedural programs become larger, more complex, it is difficult to make changes. - A change to a given variable or data structure requires changes to all of the functions operating over that variable or data structure. 3 Object Oriented Programming: Solution! An object contains - data (like fields of a struct) - functions that operate over that data! Code outside the object can access the data only via the member functions.! If the representation of the data in the object needs to change: - Only the member functions must be redefined to adapt to the changes. - The code outside the object does not need to 4 change, it accesses the object in the same way.

Object Oriented Programming: Concepts! Encapsulation: combining data and code into a single object.! Data hiding (or Information hiding) is the ability to hide the details of data representation from the code outside of the object.! Interface: the mechanism that code outside the object uses to interact with the object. - The (public) member functions - Specifically outside code needs to know only the function prototypes (not the function bodies). 5 Object Oriented Programming: Real World Example! In order to drive a car, you need to understand only its interface: - ignition switch - gas pedal, brake pedal - steering wheel - gear shifter! You don t need to understand how the steering works internally.! You can operate any car with the same interface. 6 Classes and Objects! A class is like a blueprint for an object. - a detailed description of an object. - used to make many objects. - these objects are called instances of the class.! For example, the String class in C++. - Make an instance (or two): 13.2 The Class! A class in C++ is similar to a structure. - It allows you to define a new (composite) data type.! A class contains: - variables AND - functions! These are called members String cityname1( Austin ), cityname2( Dallas ); - use member functions to manipulate the objects: int size = cityname1.length(); cityname2.insert(0, Big ); 7 Members can be: - unaccessible outside the class - accessible outside the class. 8

Example class declaration // models a 12 hour clock class Time //new data type int hour; int minute; void addhour(); ; void sethour(int); void setminute(int); int gethour() const; int getminute() const; string display() const; void addminute(); Access rules! Used to control access to members of the class! can be accessed by functions inside AND outside of the class! can be called by or accessed by only functions that are members of the class (inside) - member variables (attributes) are declared private, to hide their definitions from outside the class. - certain functions are declared public to provide (controlled) access to the hidden/private data. - these public functions form the interface to the class 9 10 Using const with member functions! const appearing after the parentheses in a member function declaration specifies that the function will not change any data in the calling object. int gethour() const; int getminute() const; string display() const;! These member functions won t change hour or minute. 11 Defining member functions! Member function definitions occur OUTSIDE of the class definition (usually in a separate file).! The name of each function is preceded by the class name and scope resolution operator (::) - void Time::setHour(int hr) hour appears to be undefined, but it is a member variable of the Time class 12

Accessors and mutators! Accessor functions (a.k.a. getters ) - returns a value from the object (without changing it)! Mutator functions (a.k.a. setters ) - Changes value(s) of member variable(s). 13 Defining Member Functions void Time::setHour(int hr) // hour is a member var void Time::setMinute(int min) minute = min; // minute is a member var int Time::getHour() const return hour; int Time::getMinute() const return minute; void Time::addHour() // a private member func if (hour == 12) hour = 1; else hour++; 14 Defining Member Functions void Time::addMinute() if (minute == 59) minute = 0; addhour(); // call to private member func else minute++; string Time::display() const // returns time in string formatted to hh:mm ostringstream sout; //include <sstream> sout.fill('0'); //padding char for setw sout << hour << ":" << setw(2) << minute; return sout.str(); 13.3 Defining an instance of the class! ClassName variable (like a structure): Time t1;! This defines t1 to contain an object of type Time (the values of hour and minute are not set).! Access public members of class with dot notation: t1.sethour(3); t1.setminute(41); t1.addminute(); 15! Use dot notation OUTSIDE class only. 16

Using the Time class Do not store stale data Time t; t.sethour(12); t.setminute(58); cout << t.display() <<endl; t.addminute(); cout << t.display() << endl; t.addminute(); cout << t.display() << endl; return 0; Output: 12:58 12:59 1:00! Why not store display string in a variable instead of composing it every time?! Because it could become stale. - If the minute or hour changes, then the data in the object would be inconsistent: - stored display string would not match new hours and minutes. Don t store any data that could become stale, compute it in a member function instead. 17 18 13.4 Setters and getters: what s the point?! Why have setters and getters that just do assignment and return values?! Why not just make the member variables public?! Setter functions can validate the incoming data. - setminute can make sure minutes are between 0 and 59 (if not, it can report an error).! Getter functions could act as a gatekeeper to the data or provide type conversion. 19 13.5 Separating Specs from Implementation! Class declarations are usually stored in their own header files (Time.h) - filename is usually same as class name.! Member function definitions are stored in a separate file (Time.cpp) - called the class implementation file - it must #include the header file,! Any program/file using the class must include the class s header file (#include Time.h ) 20

13.6 Inline member functions Member functions can be defined - after the class declaration (normally) - inline: in class declaration Inline appropriate for short function bodies: class Time int hour; int minute; int gethour() const return hour; int getminute() const return minute; void sethour(int); void setminute(int); //... class decl cont. 21 Tradeoff: Inline member functions vs. declaring them separately Separately defined member functions when called, these are executed normally: - compiler stores return address of call, allocates memory for local variables, etc. Inline member functions: Compiler copies code for an inline function into program in place of call - makes larger executable program, but no function call overhead, hence faster execution - like a macro 22 13.7 Constructors Constructor Definition A constructor is a member function with the same name as the class. It is called automatically when an object is created It performs initialization of the new object It has no return type class Time int hour; int minute; void addhour(); Time(); // Constructor prototype! Note no return type, prefixed with Class:: // file Time.cpp #include <sstream> #include <iomanip> using namespace std; #include "Time.h" Time::Time() // initializes hour and minute hour = 12; minute = 0; void Time::setHour(int hr) void Time::setMinute(int min) minute = min;... 23 24

! From main: Constructor call //using Time class (Driver.cpp) #include<iostream> #include "time.h" using namespace std; Time t; cout << t.display() <<endl; t.addminute(); cout << t.display() << endl; return 0; //Constructor called implicitly here Default Constructors! A default constructor is a constructor that takes no arguments (like Time()).! If you write a class with NO constructors, the compiler will include a default constructor for you, one that does nothing.! The original version of the Time class did not define a constructor, so the compiler provided a do-nothing constructor for it. Output: 12:00 12:01 25 26 13.8 Passing Arguments to Constructors To create a constructor that takes arguments: - Indicate parameters in prototype: class Time Time(int,int);... - Use parameters in the definition: Time::Time(int hr, int min) minute = min; // Constructor prototype Passing Arguments to Constructors Then pass arguments to the constructor when you create an object: Time t (12, 59); cout << t.display() <<endl; Output: 12:59 27 28

Classes with no Default Constructor When all of a class's constructors require arguments, then the class has NO default constructor. - C++ will NOT automatically generate a constructor with no arguments unless your class has NO constructors at all. When there are constructors, but no default constructor, you must pass the required arguments to the constructor when creating an object. 13.9 Destructors Member function that is automatically called when an object is destroyed Destructor name is ~classname, e.g., ~Time Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded, cannot take arguments If the class allocates dynamic memory, the destructor should release (delete) it 29 30 Destructors Example: class decl An alternative way to declare the PasswordManager: #include <string> using namespace std; class PasswordManager char *encryptedpassword; pwman.h PasswordManager(char *encpw); //constructor ~PasswordManager(); //destructor ; Destructors Example: member function definitions (class impl) #include "pwman.h" PasswordManager::PasswordManager(char *encpw) encryptedpassword = new char [strlen(encpw)+1]; strcpy(encryptedpassword,encpw); PasswordManager::~PasswordManager() delete [] encryptedpassword; pwman.cpp 31 32

Destructors 13.10 Overloaded Constructors Example: member function definitions (class impl) char k[] = SSS ; PasswordManager pm(k); //do stuff with pm here When is an object destroyed? - at the end of its scope //calls constructor return 0; //end of prog, pm destroyed here, calls destructor - when it is deleted (if it s dynamically allocated) 33 Recall: when 2 or more functions have the same name they are overloaded. A class can have more than one constructor - They have the same name, so they are overloaded Overloaded functions must have different parameter lists: class Time int hour; int minute; Time(); Time(int);... Time(int,int); 34! definitions: Overloaded Constructors Overloaded Constructor call! From main: #include "Time.h" Time::Time() hour = 12; minute = 0; Time::Time(int hr) minute = 0; Time::Time(int hr, int min) minute = min; Time t1; Time t2(2); Time t3(4,50); cout << t1.display() <<endl; cout << t2.display() <<endl; cout << t3.display() << endl; return 0; Output: 12:00 2:00 4:50 35 36

Overloaded Member Functions Non-constructor member functions can also be overloaded Must have unique parameter lists as for constructors 13.12 Arrays of Objects Objects can be the elements of an array: class Time int hour; int minute; Time(); Time(int); Time(int,int); void addminute(); void addminute(int);... //adds one minute //adds minutes from arg Time missedcalls[10]; //times of last 10 missed calls Default constructor is used to initialize each element when the array is defined 37 38 Arrays of Objects To invoke a constructor that takes arguments, you must use an initializer list: Time missedcalls[10] = 1,2,3,4,5,6,7,8,9,10; The constructor taking one argument is used to initialize each of the 10 Time objects here Arrays of Objects If the constructor requires more than one argument, the initializer must take the form of a function call: Time missedcalls[5] = Time(1,5), Time(2,13), Time(3,24), Time(3,55), Time(4,50); 39 40

Arrays of Objects It isn't necessary to call the same constructor for each object in an array: Accessing Objects in an Array Objects in an array are referenced using subscripts Member functions are referenced using dot notation: Time missedcalls[7] = 1, Time(2,13), Time(3,24), 4, Time(4,50); missedcalls[2].setminute(30); cout << missedcalls[4].display() << endl; If there are fewer initializers in the list than elements in the array, the default constructor will be called for all the remaining elements. 41 42