Docsity

Classes, Fields and Objects-Object Oriented Programming and Data Structures-Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Classes, Fields and Objects-Object Oriented Programming and Data Structures-Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

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

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

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 contextEach object has: � characteristics � responsibilities (or required behaviors) 8

Another example

Problem Computation modeling in biology Write a program that simulates the growth of viruspopulation in humans over time. Each virus cellreproduces itself at some time interval. Patients mayundergo drug treatment to inhibit the reproductionprocess, and clear the virus cells from their body.However, some of the cells are resistant to drugs andmay survive. 10

Write a program that simulates the growth of viruspopulation in humans over time. Each virus cellreproduces itself at some time interval. Patients mayundergo drug treatment to inhibit the reproductionprocess, and clear the virus cells from their body.However, some of the cells are resistant to drugs andmay survive. What are objects?Characteristics?Responsibilities? 11

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

Basic OOP in C++

Classes

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

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