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

Similar documents
Introduction to Classes

Lecture #1. Introduction to Classes and Objects

Abstraction in Software Development

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

System Design and Programming II

! 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

Implementing an ADT with a Class

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

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

Programming II Lecture 2 Structures and Classes

! 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

System.out.print(); Scanner.nextLine(); String.compareTo();

Function Overloading

Appendix E: Using UML in Class Design

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

Chapter 10 Introduction to Classes

1. the base class s (default) constructor is executed first, 2. followed by the derived class s constructor

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

Object Oriented Design

Introduction Of Classes ( OOPS )

Abstract Data Types. Lecture 23 Section 7.1. Robb T. Koether. Hampden-Sydney College. Wed, Oct 24, 2012

Lecture 18 Tao Wang 1

This page intentionally left blank

III. Classes (Chap. 3)

CIS 190: C/C++ Programming. Classes in C++

How to engineer a class to separate its interface from its implementation and encourage reuse.

clarity. In the first form, the access specifier public : is needed to {

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

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

PASCAL - OBJECT ORIENTED

Introduction to Programming session 24

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Abstract Data Types (ADT) and C++ Classes

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

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

Constructor - example

CS304 Object Oriented Programming Final Term

Review: C++ Basic Concepts. Dr. Yingwu Zhu

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

INHERITANCE: CONSTRUCTORS,

ADTs & Classes. An introduction

Use the dot operator to access a member of a specific object.

CSCE 110 PROGRAMMING FUNDAMENTALS

Polymorphism Part 1 1

Short Notes of CS201

CSCI 123 Introduction to Programming Concepts in C++

CS201 - Introduction to Programming Glossary By

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

Chapter 9 Classes : A Deeper Look, Part 1

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

Constructors for classes

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

CSc 328, Spring 2004 Final Examination May 12, 2004

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

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

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Classes: A Deeper Look

PIC 10A. Lecture 17: Classes III, overloading

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

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

Interview Questions of C++

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

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

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

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Programming Abstractions

Midterm Review. PIC 10B Spring 2018

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

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Classes and Data Abstraction

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Fast Introduction to Object Oriented Programming and C++

CSI33 Data Structures

C++_ MARKS 40 MIN

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

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

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

Inheritance, and Polymorphism.

Object Oriented Design

A A B U n i v e r s i t y

More C++ : Vectors, Classes, Inheritance, Templates

C++ 8. Constructors and Destructors

Praktikum: Entwicklung interaktiver eingebetteter Systeme

Functions and Recursion

Functions, Arrays & Structs

Lab 2: ADT Design & Implementation

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

TDDE18 & 726G77. Functions

#include <iostream> #include <cstdlib>

CSE 303: Concepts and Tools for Software Development

EL2310 Scientific Programming

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Transcription:

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

Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of ADTs that represent the data and its functions 3 Limitations of Procedural Programming If the data structures change, many functions must also be changed Programs that are based on complex function hierarchies are: difficult to understand and maintain difficult to modify and extend easy to break 4

Object-Oriented Programming Terminology class: like a struct (allows bundling of related variables), but variables and functions in the class can have different properties than in a struct object: an instance of a class, in the same way that a variable can be an instance of a struct 5 Classes and Objects A Class is like a blueprint and objects are like houses built from the blueprint 6

Object-Oriented Programming Terminology attributes: members of a class by default, data is private methods or behaviors: member functions of a class 7 More on Objects data hiding: restricting access to certain members of an object public interface: members of an object that are available outside of the object. This allows the object to provide access to some data and functions without sharing its internal details and design, and provides some protection from data corruption 8

13.2 Introduction to Classes 9 Introduction to Classes Objects are created from a class Format: class ClassName { }; declaration; declaration; 10

Class Example 11 Access Specifiers Used to control access to members of the class public: can be accessed by functions outside of the class private: can only be called by or accessed by functions that are members of the class 12

Class Declaration Example Private Members Public Members 13 More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private 14

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. for accessors 15 Defining a Member Function When defining a member function: Put prototype in class declaration Define function using class name and scope resolution operator (::) int Rectangle::setWidth(double w) { width = w; } 16

Accessors and Mutators Mutator: a member function that stores a value in a private member variable, or changes its value in some way Accessor: function that retrieves a value from a private member variable. Accessors do not change an object's data, so they should be marked const. 17 13.3 Defining an Instance of a Class 18

Defining an Instance of a Class An object is an instance of a class Defined like structure variables: Rectangle r; Access members using dot operator: r.setwidth(5.2); cout << r.getwidth(); Compiler error if attempt to access private member using dot operator 19 20

Program 13-1 (Continued) 21 Program 13-1 (Continued) 22

Program 13-1 (Continued) 23 Avoiding Stale Data Some data is the result of a calculation. In the Rectangle class the area of a rectangle is calculated. length x width If we were to use an area variable here in the Rectangle class, its value would be dependent on the length and the width. If we change length or width without updating area, then area would become stale. To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable. 24

Pointer to an Object Can define a pointer to an object: Rectangle *rptr; Can access public members via pointer: rptr = &otherrectangle; rptr->setlength(12.5); cout << rptr->getlength() << endl; 25 Dynamically Allocating an Object We can also use a pointer to dynamically allocate an object. 26

13.4 Why Have Private Members? 27 Why Have Private Members? Making data members private provides data protection Data can be accessed only through public functions Public functions define the class s public interface 28

Code outside the class must use the class's public member functions to interact with the object. 29 13.5 Separating Specification from Implementation 30

Separating Specification from Implementation Place class declaration in a header file that serves as the class specification file. Name the file ClassName.h, for example, Rectangle.h Place member function definitions in ClassName.cpp, for example, Rectangle.cpp File should #include the class specification file Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions 31 See Rectangle Version 1 and Pr13-4.cpp Preprocessor directives #ifndef include guard if not defined #define then include these lines in the program. Prevents including the Rectangle.h header file more than once. Several programs might have #include Rectangle.h 32

#include Rectangle.h for your own class specification file, in the current directory #include <iostream> for C++ system header files located in the compiler s include file directory, where all the standard C++ header files are located. 33 See Figure 13-15 Compile Rectangle.cpp into Rectangle.obj. This is not a complete program, so you cannot create an executable. Rectangle.h is included and its info is in the object file too. Compile the main program file Pr13-4.cpp into the object file Pr13-4.obj. It s not complete, so you cannot create an executable. Link Pr13-4.obj and Rectangle.obj into the executable file Pr13-4.exe 34

cl.exe cl /c Pr13-4.cpp compile only cl /c Pr13-4.cpp Rectangle.cpp (auto compiles with files included) Now you should have Pr13-4.obj and Rectangle.obj (which includes the info from Rectangle.h) link Pr13-4.obj Rectangle.obj First one in the list becomes Pr13-4.exe Pr13-4 Run it 35 g++ g++ -c Pr13-4.cpp compiles Now you should have Pr13-4.obj and Rectangle.obj (which includes the info from Rectangle.h) g++ -o main Pr13-4.obj Rectangle.obj Link into executable file named main.exe Also learn about make, project Visual Studio. See Appendix M or XCode tutorial 36

13.6 Inline Member Functions 37 Inline Member Functions Member functions can be defined inline: in class declaration after the class declaration Inline appropriate for short function bodies: int getwidth() const { return width; } 38

Rectangle Class with Inline Member Functions 1 // Specification file for the Rectangle class 2 // This version uses some inline member functions. 3 #ifndef RECTANGLE_H 4 #define RECTANGLE_H 5 6 class Rectangle 7 { 8 private: 9 double width; 10 double length; 11 public: 12 void setwidth(double); //still defined in Rectangle.cpp 13 void setlength(double); 14 15 double getwidth() const //these are the inline fucntions 16 { return width; } 17 18 double getlength() const 19 { return length; } 20 21 double getarea() const 22 { return width * length; } 23 }; 24 #endif 39 Tradeoffs Inline vs. Regular Member Functions Regular functions when called, compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into program in place of call larger executable program, but no function call overhead, hence faster execution 40

13.7 Constructors 41 Constructors Member function that is automatically called when an object is created Purpose is to construct an object Constructor function name is class name Has no return type See Pr13-5.cpp 42

43 Continues... 44

Contents of Rectangle.ccp Version3 (continued) 45 46

Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a default constructor for you, one that does nothing. A simple instantiation of a class (with no arguments) calls the default constructor: Rectangle r; Default constructors and dynamically allocated objects: Won t call constructor: Rectangle *rptr; Will call constructor: rptr = new Rectangle; 47 13.8 Passing Arguments to Constructors 48

Passing Arguments to Constructors To create a constructor that takes arguments: indicate parameters in prototype: Rectangle(double, double); Use parameters in the definition: Rectangle::Rectangle(double w, double len) { width = w; length = len; } 49 Passing Arguments to Constructors You can pass arguments to the constructor when you create an object: Rectangle r(10, 5); 50

More About Default Constructors If all of a constructor's parameters have default arguments, then it is a default constructor. For example: Rectangle(double = 0, double = 0); Now you cannot have a no-arg constructor. Creating an object and passing no arguments will cause this constructor to execute: Rectangle r; 51 Rectangle(double, double = 0); Not all parameters need default arguments. In this case, a noarg default constructor is allowed. 52

Classes with No Default Constructor When all of a class's constructors require arguments, then the class has NO default constructor. When this is the case, you must pass the required arguments to the constructor when creating an object. 53 13.9 Destructors 54

Destructors Member function automatically called when an object is destroyed. Shutdown purposes Destructor name is ~classname, e.g., ~Rectangle() Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded If constructor allocates dynamic memory, destructor should release it See Pr13-10.cpp 55 Destructors See ContactInfo.h (Version1) and Pr13-11.cpp allocates just enough memory for name and phone number Destructors and Dynamically Allocated Class Objects ContactInfo *objectptr; objectptr = new ContactInfo( Al, 123-4567 ); //dynamically create object delete objectptr; //destroy the dynamically created object. Destructor is automatically called 56

57 Contents of InventoryItem.h Version1 (Continued) 58

59 60

Constructors, Destructors, and Dynamically Allocated Objects When an object is dynamically allocated with the new operator, its constructor executes: Rectangle *r = new Rectangle(10, 20); When the object is destroyed, its destructor executes: delete r; 61 13.10 Overloading Constructors 62

Overloading Constructors A class can have more than one constructor Overloaded constructors in a class must have different parameter lists: Rectangle(); Rectangle(double); Rectangle(double, double); See InventoryItem.h and Pr13-12.cpp 63 Continues... 64

65 Only One Default Constructor and One Destructor Do not provide more than one default constructor for a class: one that takes no arguments and one that has default arguments for all parameters Square(); Square(int = 0); // will not compile Since a destructor takes no arguments, there can only be one destructor for a class 66

Other Overloaded Member Functions The InventoryItem class could have overloaded the setcost function void setcost(double c) {cost = c;} void setcost(string c) {cost = atof(c.c_str());} 67 Member Function Overloading Non-constructor member functions can also be overloaded: void setcost(double); void setcost(char *); Must have unique parameter lists as for constructors 68

13.11 Using Private Member Functions 69 Using Private Member Functions A private member function can only be called by another member function It is used for internal processing by the class, not for use outside of the class See the createdescription function in ContactInfo.h (Version 2) initname and initphone are private because they should only be called from the constructor 70

13.12 Arrays of Objects 71 Arrays of Objects Objects can be the elements of an array: InventoryItem inventory[40]; Default constructor for object is used when array is defined 72

Arrays of Objects Must use initializer list to invoke constructor that takes arguments: InventoryItem inventory[3] = { "Hammer", "Wrench", "Pliers" }; //matches with the second constructor If there s no default constructor, you must provide the initializer list. 73 Arrays of Objects If the constructor requires more than one argument, the initializer must take the form of a function call: 74

Arrays of Objects It isn't necessary to call the same constructor for each object in an array: 75 Accessing Objects in an Array Objects in an array are referenced using subscripts Member functions are referenced using dot notation: inventory[2].setunits(30); cout << inventory[2].getunits(); 76

77 Program 13-3 (Continued) 78

13.15 The Unified Modeling Language 79 The Unified Modeling Language UML stands for Unified Modeling Language. The UML provides a set of standard diagrams for graphically depicting object-oriented systems 80

UML Class Diagram A UML diagram for a class has three main sections. 81 Example: A Rectangle Class class Rectangle { private: double width; double length; public: bool setwidth(double); bool setlength(double); double getwidth() const; double getlength() const; double getarea() const; }; 82

UML Access Specification Notation In UML you indicate a private member with a minus (-) and a public member with a plus(+). These member variables are private. These member functions are public. 83 UML Data Type Notation To indicate the data type of a member variable, place a colon followed by the name of the data type after the name of the variable. - width : double - length : double 84

UML Parameter Type Notation To indicate the data type of a function s parameter variable, place a colon followed by the name of the data type after the name of the variable. + setwidth(w : double) 85 UML Function Return Type Notation To indicate the data type of a function s return value, place a colon followed by the name of the data type after the function s parameter list. + setwidth(w : double) : void 86

The Rectangle Class 87 Showing Constructors and Destructors No return type listed for constructors or destructors Constructors Destructor 88