6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang



Similar documents
The C Programming Language course syllabus associate level

Object Oriented Software Design II

El Dorado Union High School District Educational Services

Curriculum Map. Discipline: Computer Science Course: C++

C++ Programming Language

Chapter 6: Programming Languages

Programming Languages

Glossary of Object Oriented Terms

How To Teach C++ Data Structure Programming

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

6.S096 Lecture 1 Introduction to C

An Incomplete C++ Primer. University of Wyoming MA 5310

CSCI 3136 Principles of Programming Languages

Lecture 1: Introduction

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Moving from CS 61A Scheme to CS 61B Java

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

CSC Software II: Principles of Programming Languages

Fall 2012 Q530. Programming for Cognitive Science

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

History OOP languages Year Language 1967 Simula Smalltalk

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

CEC225 COURSE COMPACT

Chapter 3.2 C++, Java, and Scripting Languages. The major programming languages used in game development.

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

ECS 165B: Database System Implementa6on Lecture 2

CSE 307: Principles of Programming Languages

Syllabus for CS 134 Java Programming

Semester Review. CSC 301, Fall 2015

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Java (12 Weeks) Introduction to Java Programming Language

Web development... the server side (of the force)

1/20/2016 INTRODUCTION

CS 6371: Advanced Programming Languages

Welcome to Introduction to Computers and Programming Course using Python

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Evolution of the Major Programming Languages

Object Oriented Software Design II

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

McGraw-Hill The McGraw-Hill Companies, Inc.,

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

C++ INTERVIEW QUESTIONS

CS11 Advanced C++ Spring Lecture 9 (!!!)

Facebook Twitter YouTube Google Plus Website

An Internet Course in Software Development with C++ for Engineering Students

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Chapter 1. Dr. Chris Irwin Davis Phone: (972) Office: ECSS CS-4337 Organization of Programming Languages

C++ Overloading, Constructors, Assignment operator

OKLAHOMA SUBJECT AREA TESTS (OSAT )

Advanced Data Structures

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Software Engineering Techniques

BCS2B02: OOP Concepts and Data Structures Using C++

Crash Course in Java

What is a programming language?

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

Binary storage of graphs and related data

Variable Base Interface

Sources: On the Web: Slides will be available on:

Functional Programming

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Java EE Web Development Course Program

Programming Languages & Tools

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

CSE 130 Programming Language Principles & Paradigms

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

CS A250 (CRN ) C++ Programming Language 2. Syllabus Fall 2015

LINKED DATA STRUCTURES

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Exploring Algorithms with Python

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

Fast Arithmetic Coding (FastAC) Implementations

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Introduction to Object-Oriented Programming

Lecture Data Types and Types of a Language

Comp151. Definitions & Declarations

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Chapter 13: Program Development and Programming Languages

Lecture Notes on Binary Search Trees

CIS 190: C/C++ Programming. Polymorphism

Brent A. Perdue. July 15, 2009

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

CS 106 Introduction to Computer Science I

Fundamentals of Java Programming

COMPARISON OF OBJECT-ORIENTED AND PROCEDURE-BASED COMPUTER LANGUAGES: CASE STUDY OF C++ PROGRAMMING

Fundamentals of Programming Languages

Transcription:

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Today s topics Why objects? Object-oriented programming (OOP) in C++ classes fields & methods objects representation invariant 2

Why objects?

At the end of the day... computers just manipulate 0 s and 1 s Figure by MIT OpenCourseWare.

But binary is hard (for humans) to work with 5

Towards a higher level of abstraction? declarative languages (Haskell, ML, Prolog...) OO languages (C++, Java, Python...) procedural languages (C, Fortran, COBOL...) assembly languages binary code 6 Figure by MIT OpenCourseWare.

There are always trade-offs High-level languages simpler to write & understand more library support, data structures Low-level languages closer to hardware more efficient (but also dangerous!) What about C++? 7

What are objects? Objects model elements of the problem context Each object has: characteristics responsibilities (or required behaviors) 8

Example Problem Design and build a computer hockey game Object Hockey player Characteristics Position, height, weight, salary, number of goals Responsibilities Pass the puck, shoot, skate forward, skate backward, punch another player, etc. 9

Another example Problem Computation modeling in biology Write a program that simulates the growth of virus population in humans over time. Each virus cell reproduces itself at some time interval. Patients may undergo drug treatment to inhibit the reproduction process, and clear the virus cells from their body. However, some of the cells are resistant to drugs and may survive. 10

Write a program that simulates the growth of virus population in humans over time. Each virus cell reproduces itself at some time interval. Patients may undergo drug treatment to inhibit the reproduction process, and clear the virus cells from their body. However, some of the cells are resistant to drugs and may survive. What are objects? Characteristics? Responsibilities? 11

Write a program that simulates the growth of virus population in humans over time. Each virus cell reproduces itself at some time interval. Patients may undergo drug treatment to inhibit the reproduction process, and clear the virus cells from their body. However, some of the cells are resistant to drugs and may survive. What are objects? Characteristics? Responsibilities? 12

Patient characteristics virus population immunity to virus (%) responsibilities take drugs Virus characteristics reproduction rate (%) resistance (%) responsibilities reproduce survive 13

Questions Why didn t we model an object named Doctor? Surely, most hospitals have doctors, right? 14

Questions Why didn t we model an object named Doctor? Surely, most hospitals have doctors, right? Doesn t every patient have an age? Gender? Illness? Symptoms? Why didn t we model them as characteristics? 15

Basic OOP in C++

Classes A class is like a cookie cutter; it defines the shape of objects Objects are like cookies; they are instances of the class Photograph courtesy of Guillaume Brialon on Flickr. 17

Classes: Declaration vs. definition client depends declaration implements definition Declaration (.h files) list of functions & fields including functions that the class promises to its client it s like a contract Definition (.cc files) implementation of functions 18

Class declaration

Class declaration class Virus { }; float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); 20

class name field class Virus { float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: constructors Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); }; method don t forget the semi-colon! 21

Fields (characteristics) class Virus { }; float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); 22

Methods (responsibilities) class Virus { }; float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); 23

Constructors class Virus { float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: }; Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); Note the special syntax for constructor (no return type!) 24

Access control: public vs. private class Virus { // rate of reproduction, in % float reproductionrate; float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; }; public: private Virus(float newresistance); Virus(float newreproductionrate, float newresistance); public Virus* reproduce(float immunity); bool survive(float immunity); private: can only be accessed inside the class public: accessible by anyone 25

How do we decide private vs. public? Client depends Interface satisfies Implementation interface: parts of class that change infrequently (e.g. virus must be able to reproduce) implementation: parts that may change frequently (e.g. representation of resistance inside virus) 26

Protect your private parts! Client Interface Implementation Why is this bad? X 27

Access control: public vs. private class Virus { // rate of reproduction, in % float reproductionrate; float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; }; public: private Virus(float newresistance); Virus(float newreproductionrate, float newresistance); public Virus* reproduce(float immunity); bool survive(float immunity); In general, keep member fields as private minimize the amount of public 28 parts

Access control: constant fields class Virus { }; float reproductionrate; // rate of reproduction, in % float resistance; // resistance against drugs, in % static const float defaultreproductionrate = 0.1; public: Virus(float newresistance); Virus(float newreproductionrate, float newresistance); Virus* reproduce(float immunity); bool survive(float immunity); Why make it a constant? Why not just declare it as a normal field? 29

Class definition

Class definition #<stdlib.h> #include Virus.h Virus::Virus(float newresistance) { reproductionrate = defaultreproductionrate; resistance = newresistance; } Virus::Virus(float newreproductionrate, float newresistance) { reproductionrate = newreproductionrate; resistance = newresistance; } // If this virus cell reproduces, // returns a new offspring with identical genetic info. // Otherwise, returns NULL. Virus* Virus::reproduce(float immunity) { float prob = (float) rand() / RAND_MAX; // generate number between 0 and 1 // If the patient's immunity is too strong, it cannot reproduce if (immunity > prob) return NULL; // Does the virus reproduce this time? if (prob > reproductionrate) return NULL; // No! } return new Virus(reproductionRate, resistance); // Returns true if this virus cell survives, given the patient's immunity bool Virus::survive(float immunity) { // If the patient's immunity is too strong, then this cell cannot survive if (immunity > resistance) return false; } return true; const float Virus::defaultReproductionRate; 31

Header inclusion #include <stdlib.h> #include "Virus.h" Virus::Virus(float newresistance) { reproductionrate = defaultreproductionrate; resistance = newresistance; } Virus::Virus(float newreproductionrate, float newresistance) { reproductionrate = newreproductionrate; resistance = newresistance; } 32

Constructor definition #include <stdlib.h> #include "Virus.h" Virus::Virus(float newresistance) { reproductionrate = defaultreproductionrate; resistance = newresistance; } Virus::Virus(float newreproductionrate, float newresistance) { reproductionrate = newreproductionrate; resistance = newresistance; } Remember to initialize all fields inside constructors! 33

Constructor definition Can also do: Virus::Virus(float newreproductionrate, float newresistance) { reproductionrate = newreproductionrate; resistance = newresistance; } Virus::Virus(float newreproductionrate, float newresistance) : reproductionrate(newreproductionrate), resistance(newresistance) { } 34

Method definition // Returns true if this virus cell survives, // given the patient's immunity bool Virus::survive(float immunity) { // If the patient's immunity is too strong, // then this cell cannot survive if (immunity > resistance) return false; } return true; 35

Working with objects

Patient class declaration #include Virus.h #define MAX_VIRUS_POP 1000 class Patient { Virus* viruspop[max_virus_pop]; int numviruscells; float immunity; // degree of immunity, in % public: }; Patient(float initimmunity, int initnumviruses); ~Patient(); void takedrug(); bool simulatestep(); 37

Patient class declaration #include Virus.h #define MAX_VIRUS_POP 1000 Array of pointers to objects class Patient { Virus* viruspop[max_virus_pop]; int numviruscells; float immunity; // degree of immunity, in % Constructor public: }; Patient(float initimmunity, int initnumviruses); ~Patient(); void takedrug(); bool simulatestep(); Destructor 38

Static object allocation class Patient {... public: Patient(float initimmunity, int initnumviruses);... }; int main() { float initimmunity = 0.1; int initnumviruscells = 5; Patient p(0.1, 5); } p.takedrug(); 39

Calling the constructor class Patient {... public: Patient(float initimmunity, int initnumviruses);... }; int main() { float initimmunity = 0.1; int initnumviruscells = 5; Patient p(0.1, 5); } p.takedrug(); 40

Deleting statically allocated objects class Patient {... public: Patient(float initimmunity, int initnumviruses);... }; int main() { float initimmunity = 0.1; int initnumviruscells = 5; Patient p(0.1, 5); } p.takedrug(); Automatically destroyed at the end of scope 41

Objects on heap To allocate an object on heap: use new keyword (analogous to malloc ) To deallocate: use delete keyword (analogous to free ) Patient* p = new Patient(0.1, 5);... delete p; 42

Dynamic object creation: Example Patient::Patient(float initimmunity, int initnumviruscells) { float resistance; immunity = initimmunity; for (int i = 0; i < initnumviruscells; i++) { //randomly generate resistance, between 0.0 and 1.0 resistance = (float) rand()/rand_max; } viruspop[i] = new Virus(resistance); } numviruscells = initnumviruscells; 43

Using dynamically allocated objects bool Patient::simulateStep() { Virus* virus; bool survived = false;... for (int i = 0; i < numviruscells; i++){ virus = viruspop[i]; survived = virus->survive(immunity); } if (survived) {... } else {... }... 44

What happens during destruction? The destructor is automatically called Patient::~Patient(){ for (int i = 0; i < numviruscells; i++){ delete viruspop[i]; } } Patient* p = new Patient(0.1, 5);... delete p; But why didn t we have a destructor for Virus? 45

Representation invariant

Representation invariant Statements about characteristics of objects defines what it means for an object to be valid e.g. Every IKEA coffee table must have four legs Valid Invalid 47 Figures by MIT OpenCourseWare.

Example class Patient { }; Virus* viruspop[max_virus_pop]; int numviruscells; float immunity; // degree of immunity, in % public: Patient(float initimmunity, int initnumviruses); ~Patient(); void takedrug(); bool simulatestep(); What are the representation invariants for Patient? 48

Rep. invariant violation void Patient::takeDrug(){ immunity = immunity + 0.1; } What s wrong with this method? 49

Preserving rep. invariant bool Patient::checkRep() { return (immunity >= 0.0) && (immunity < 1.0) && (numviruscells >= 0) && (numviruscells < MAX_VIRUS_POP); } checkrep returns true if and only if the rep. invariants hold true call checkrep at the beginning and end of every public method call checkrep at the end of constructors 50

Preserving rep. invariant #include <cassert> class Patient {... bool checkrep(); public:... }; void Patient::takeDrug() { assert(checkrep());... assert(checkrep()); } Patient::Patient(float initimmunity, int initnumviruses) {... assert(checkrep()); } 51

Preserving rep. invariant Will calling checkrep() slow down my program? Yes, but you can take them out once you are confident about your code. 52

Until next time... Homework #4 (due 11:59 PM Monday) implementing BSTs using classes Next lecture inheritance & polymorphism templates 53

References Thinking in C++ (B. Eckel) Free online edition! Essential C++ (S. Lippman) Effective C++ (S. Meyers) C++ Programming Language (B. Stroustrup) Design Patterns (Gamma, Helm, Johnson,Vlissides) Object-Oriented Analysis and Design with Applications (G. Booch, et. al) 54

MIT OpenCourseWare http://ocw.mit.edu 6.088 Introduction to C Memory Management and C++ Object-Oriented Programming January IAP 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.