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

Similar documents
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

! 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

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

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

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

Procedural Programming

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

Introduction to Classes

A Deeper Look at Classes

Chapter 9 Classes : A Deeper Look, Part 1

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

Overloading Operators

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

Computer Programming with C++ (21)

System Design and Programming II

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

Classes: A Deeper Look

Introduction to Programming session 24

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

Fundamentals of Programming Session 24

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>

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

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

III. Classes (Chap. 3)

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

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

57:017, Computers in Engineering C++ Classes

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

C++ Classes, Constructor & Object Oriented Programming

Introduction Of Classes ( OOPS )

Functions, Arrays & Structs

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

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

Abstraction in Software Development

by Pearson Education, Inc. All Rights Reserved. 2

IS 0020 Program Design and Software Tools

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

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)

Lecture #1. Introduction to Classes and Objects

CS304 Object Oriented Programming Final Term

Object Oriented Design

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:

Chapter 6: Classes and Data Abstraction

Chapter 10 Introduction to Classes

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

Classes: A Deeper Look. Systems Programming

Fast Introduction to Object Oriented Programming and C++

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

Operator Overloading

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

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

CPSC 427: Object-Oriented Programming

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

CS24 Week 3 Lecture 1

Functions, Arrays & Structs

Data Structures using OOP C++ Lecture 3

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

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

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

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Scope. Scope is such an important thing that we ll review what we know about scope now:

Constructor - example

CSCE 110 PROGRAMMING FUNDAMENTALS

Friends and Overloaded Operators

CS 247: Software Engineering Principles. ADT Design

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

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

Friends and Overloaded Operators

PIC 10A Objects/Classes

Object Oriented Design

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

Lecture 18 Tao Wang 1

CS313D: ADVANCED PROGRAMMING LANGUAGE

C++ For Science and Engineering Lecture 15

Review Questions for Final Exam

CS3157: Advanced Programming. Outline

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

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

CMSC 202 Midterm Exam 1 Fall 2015

Introduction & Review

Chapter 16: Classes and Data Abstraction

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Ch 6. Functions. Example: function calls function

Pointers. Developed By Ms. K.M.Sanghavi

CS 1337 Computer Science II Page 1

Transcription:

Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Spring 2017 Jill Seaman 1 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 - functions (these manipulate the variables) l These are called members l A class declaration defines the member variables and the prototypes of the member functions. 2 Example class declaration Access specifiers // 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(); 3 l Used to control access to members of the class - public members can be accessed by functions inside AND outside of the class - private members can be called or accessed only from functions inside the class (the class s member functions) Private is the default setting for class members. l Member variables are declared private, to hide their definitions from outside the class. l Certain functions are declared public to provide controlled access to the hidden/private data. - these public functions form the interface to the 4class

Using const with member functions Accessors and mutators l const appearing after the parentheses in a member function declaration specifies that the function will not change any data inside the object. int gethour() const; int getminute() const; string display() const; l These member functions won t change hour or minute. l Other functions may or may not change them. l using const is optional. 5 l Accessor functions - return a value from the object (without changing it) - can be defined using const. - a getter is a special accessor function that returns the value of one member variable l Mutator functions - Change the value(s) of member variable(s). - a setter is a special mutator function that changes (sets) the value of one member variable. 6 Defining member functions l Member function definitions usually occur after of the class definition. l 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 7 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++; 8

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 string hourstring = to_string(hour); string minutestring = to_string(minute); if (minutestring.length()==1) minutestring = "0" + minutestring; return hourstring + ":" + minutestring; to_string(int): converts an int to string. string.length(): returns number of chars in string. str1+str2: returns a new string formed by adding chars of str1 followed by chars of str2. 9 l 13.3 Defining an instance of the class ClassName variable; l This defines t1 to contain an object of type Time (with hour and minute members). l Then access public members of class with dot notation: Time t1; t1.sethour(3); t1.setminute(41); t1.addminute(); like declaring a structure variable calls to member functions 10 Using the Time class Time t; t.sethour(12); t.setminute(58); cout << t.display() <<endl; t.addminute(); cout << t.display() << endl; t.addminute(); cout << t.display() << endl; Output: 12:58 12:59 1:00 Note: the program includes the code from slides 3, 8, 9, and 11 (and any #includes needed). See AllTime.cpp in Time.zip 11 13.1 Procedural Programming A style of programming in which: l Data is stored in variables - Perhaps using arrays and structs. l Program is a collection of functions that perform operations over the variables - Good example: PA2 inventory program l Variables are passed to the functions as arguments Focus is on organizing and implementing the functions. 12

Procedural Programming: Problem l It is not uncommon for - program specifications to change - representations of data to be changed for internal improvements. l As procedural programs become larger and 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. l Example: use vectors or linked lists instead of Object Oriented Programming: Solution l An object (instance of a class) contains - data (like fields of a struct) - functions that operate over that data l Code outside the object can access the data only through the object s functions. l If the representation of the data inside the object needs to change: - Only the object s function definitions must be redefined to adapt to the changes. - The code outside the object does not need to change, it accesses the object in the same way. 13 14 arrays for the inventory Object Oriented Programming: Concepts l Encapsulation: combining data and code into a single object. l Data hiding (or Information hiding) is the ability to hide the details of data representation from the code outside of the object. l Interface: the mechanism that code outside the object uses to interact with the object. - The object s (public) functions - Specifically, outside code needs to know only the function prototypes (not the function bodies). 15 Object Oriented Programming: Real World Example l In order to drive a car, you need to understand only its interface: - ignition switch - gas pedal, brake pedal - steering wheel - gear shifter l You don t need to understand how the steering works internally. l You can operate any car with the same interface. 16

Classes and Objects l 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. l For example, the string class in C++. - Make an instance (or two): string cityname1= Austin, cityname2= Dallas ; - use the object s functions to work with the objects: int size = cityname1.length(); cityname2.append( Cowboys ); 17 13.5 Separating Specs from Implementation l Class declarations are usually stored in their own header files (Time.h) - called the specification file l Member function definitions are stored in a separate file (Time.cpp) - called the class implementation file l Main function and standalone functions go in a third file (Driver.cpp) See the Multi-file Development Lecture and TimeDemo.zip 18 13.6 Inline member functions Member functions can be defined - after the class declaration (normally) OR - inline: in class declaration Inline is appropriate for short function bodies: class Time { int hour; int minute; void addhour(); // not inlined int gethour() const { return hour; int getminute() const { return minute; void sethour(int h) { hour = h; void setminute(int m) { minute = m; string display() const; //not inlined void addminute(); //not inlined ; 19 13.7 Constructors 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... 20

Constructor Definition l 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; 21 l 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; Output: //Constructor called implicitly here 12:00 12:01 22 13.8 Passing Arguments to Constructors To create a constructor that takes arguments: - Indicate the parameters in the prototype: class Time { Time(int,int);... - Use the parameters in the definition: Time::Time(int hr, int min) { minute = min; // Constructor prototype Passing Arguments to Constructors Pass arguments to the constructor when you create an object (in the declaration): Time t (12, 59); cout << t.display() <<endl; Output: 12:59 23 24

Default Constructors l A default constructor is a constructor that takes no arguments (like Time()). l If you write a class with NO constructors, the compiler will include a default constructor for you, one that does (almost) nothing. l The original version of the Time class did not define a constructor, so the compiler provided a constructor for it. 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. 25 26 13.9 Destructors 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 (it cannot be overloaded, cannot take arguments). If the class dynamically allocates memory, the destructor should release (delete) it 27 Example: Inventory class, with dynamically allocated array: struct Product { string productname; string locator; int quantity; double price; ; Inventory.h // product description // used to find product // number of copies in inventory // selling price of the product class Inventory { Product *products; //dynamically allocated array int count; Inventory (int); ~Inventory(); //destructor bool additem(product); int removeitem(string); void showinventory(); 28

Destructors Example: member function definitions for constructor and destructor: Destructors Example: driver creates and destroys an Inventory #include "Inventory.h" Inventory.cpp Inventory storeproducts(100); //calls constructor Inventory::Inventory(int size){ products = new Product[size]; //dynamic allocation count = 0; //do stuff with storeproducts here //end of main, storeproducts object destroyed here, // calls its destructor (deletes products array) Inventory::~Inventory() { delete [] products; 29 When is an object destroyed? - at the end of its scope OR - when it is deleted (if it s dynamically allocated) 30 13.10 Overloaded Constructors Overloaded Constructors Recall: when 2 or more functions have the same name they are overloaded. A class can have more than one constructor function - 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); l definitions: #include "Time.h" Time::Time() { hour = 12; minute = 0; Time::Time(int hr) { minute = 0; Time::Time(int hr, int min) { minute = min;... 31 32

Overloaded Constructor call 13.12 Arrays of Objects l From main: Time t1; Time t2(2); Time t3(4,50); cout << t1.display() <<endl; cout << t2.display() <<endl; cout << t3.display() << endl; Output: 12:00 2:00 4:50 33 An array can contain objects (the element type can be a Class): Time recentcalls[10]; //times of last 10 phone calls The default constructor (Time()) is used to initialize each element of the array when it is created. This array is initialized to 10 Time objects, each set to 12:00. To invoke a constructor that takes arguments, you must use an initializer list... 34 Arrays of Objects initializer lists Accessing Objects in an Array Each initializer takes the form of a function call: Time recentcalls[7] = {Time(1), Time(2,13), Time(3,24), Time(4), Time(4,50); If there are fewer initializers in the list than elements in the array, the default constructor will be called for all the remaining elements. This array is initialized to 7 Time objects, set to 1:00, 2:13, 3:24, 4:00, 4:50, 12:00 and 12:00. 35 Objects in an array are referenced using subscripts Member functions are referenced using dot notation Must access the specific object in the array BEFORE calling the member function: recentcalls[2].setminute(30); cout << recentcalls[4].display() << endl; Processing array elements in a loop: for (int i=0; i<7; i++) cout << recentcalls[i].display() << ; cout << endl; 36

Composition l When one class contains another as a member: #include Time.h" Calls.h class Calls { Time calls[10]; // times of 10 phone calls // this array is initialized using default constructor void set(int,time); void displayall(); #include <iostream> using namespace std; #include "Calls.h" void Calls::set(int i, Time t) { calls[i] = t; void Calls::displayAll () { for (int i=0; i<10; i++) { calls[i].display(); //calls member function cout << ; Calls.cpp 37 l Driver for Calls Composition //Example using Calls and Time classes #include<iostream> using namespace std; #include Calls.h //this includes Time.h Calls calltimes; Time t1(4,30); calltimes.set(0,t1); Time t2(11,42); calltimes.set(1,t2); Output: calltimes.displayall(); cout << endl; 4:30 11:42 12:0 12:0 12:0 12:0 12:0 12:0 12:0 12:0 38