Ch 7-1. Object-Oriented Programming and Classes



Similar documents
EP241 Computer Programming

Computer Programming C++ Classes and Objects 15 th Lecture

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

Glossary of Object Oriented Terms

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

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

C++ INTERVIEW QUESTIONS

13 Classes & Objects with Constructors/Destructors

Note: Syntactically, a ; is needed at the end of a struct definition.

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

C++FA 5.1 PRACTICE MID-TERM EXAM

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

Course notes Standard C++ programming

CS 111 Classes I 1. Software Organization View to this point:

CISC 181 Project 3 Designing Classes for Bank Accounts

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

7.7 Case Study: Calculating Depreciation

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

Basics of I/O Streams and File I/O

C++ Programming Language

Member Functions of the istream Class

Friends and Overloaded Operators

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

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

Goals for This Lecture:

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

AP Computer Science Java Subset

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Appendix K Introduction to Microsoft Visual C++ 6.0

Advanced Data Structures

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

Comp151. Definitions & Declarations

El Dorado Union High School District Educational Services

The C Programming Language course syllabus associate level

Chapter 5 Functions. Introducing Functions

CS 101 Computer Programming and Utilization

Sequential Program Execution

Course Title: Software Development

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

COSC 181 Foundations of Computer Programming. Class 6

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

Moving from C++ to VBA

Java Application Developer Certificate Program Competencies

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

Basics of C++ and object orientation in OpenFOAM

OKLAHOMA SUBJECT AREA TESTS (OSAT )

Angular Velocity vs. Linear Velocity

Moving from CS 61A Scheme to CS 61B Java

Object Oriented Software Design II

A.4 The Solar System Scale Model

Conditions & Boolean Expressions

While Loop. 6. Iteration

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Chapter 1: Key Concepts of Programming and Software Engineering

Basic Programming and PC Skills: Basic Programming and PC Skills:

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Fundamentals of Java Programming

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

Illustration 1: Diagram of program function and data flow

Computer Programming I

6. Control Structures

x Distance of the Sun to planet

J a v a Quiz (Unit 3, Test 0 Practice)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

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

CS 241 Data Organization Coding Standards

C++ Crash Kurs. C++ Object-Oriented Programming

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Brent A. Perdue. July 15, 2009

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

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Data Structures using OOP C++ Lecture 1

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Automation of Library (Codes) Development for Content Management System (CMS)

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Toilet Paper Solar System

Chapter 25.1: Models of our Solar System

Passing 1D arrays to functions.

Facebook Twitter YouTube Google Plus Website

Appendix M: Introduction to Microsoft Visual C Express Edition

Syllabus OBJECT ORIENTED PROGRAMMING C++

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

Background Information Students will learn about the Solar System while practicing communication skills.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

CEC225 COURSE COMPACT

The separation principle : a principle for programming language design

Compiler Construction

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Lesson Name: Introduction of OOP

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Computer Programming I

How Big is our Solar System?

Transcription:

2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr)

Outline Classes Object-Oriented Programming Concept Defining, member functions Public and private members Accessor and mutator functions Structures vs. classes ch 7-1 - 2

Major Considerations in Large-scale Software System Developments Procedure of Design, Development and Maintenance of Large-Scale Software Requirements analysis Software design Unit testing Component testing System testing Maintenance Major Considerations Clear unit/component/sub-system interface Stability of unit/component/sub-system Easy modification/update of unit/component/sub-system without great impact on other parts Easy employment of new technology for unit/component/sub-system ch 7-1 - 3

Object-Oriented Programming (OOP) Object-Oriented Programming Object-oriented programming (OOP) (객체 지향형 프로그래밍) an approach to designing modular, reusable software systems a programming paradigm that represents the concept of "objects" that have data fields (attributes that describe the object) and associated procedures known as methods Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs Goals of object-oriented programming : Increased understanding: rather than talking about database tables and programming subroutines, the developer talks about things the user is familiar with: objects from their application domain Ease of maintenance and adoption of new technologies by the use of encapsulation and information hiding Ease of evolution by the use of inheritance and polymorphism ch 7-1 - 4

Similar to structures Classes Not only, just member data But also, adds member functions Integral to object-oriented programming Focus on objects Object: Contains data and operations Class: mold (주형 형틀, 거푸집) to instantiate an object In C++, variables of class type are objects ch 7-1 - 5

Class Definitions Defined similar to structures Example: class DayOfYear // name of new class type { public: // access specifier void output(); // member function int month; // data member int day; // data member }; Notice only member function s prototype Function s implementation is elsewhere ch 7-1 - 6

Declaring Objects Declared same as all variables Predefined types, structure types Example: DayOfYear today, birthday; Declares two objects of class type DayOfYear Objects include: Data (attribute) Members: month, day Operations (member functions) output() ch 7-1 - 7

Class Member Access Members accessed same as structures Example: today.month today.day And to access member function: today.output(); Invokes member function ch 7-1 - 8

Class Member Functions Must define or "implement" class member functions Like other function definitions Can be after main() definition Must specify class: void DayOfYear::output() { } :: is scope resolution operator Instructs compiler "what class" member is from Item before :: called type qualifier ch 7-1 - 9

Class Member Functions Definition Notice output() member function s definition (in next example) Refers to member data of class No qualifiers Function used for all objects of the class Will refer to "that object s" data when invoked Example: today.output(); Displays "today" object s data ch 7-1 - 10

Complete Class Example: Display 6.3 Class With a Member Function (1 of 4) ch 7-1 - 11

Display 6.3 Class With a Member Function (2 of 4) ch 7-1 - 12

Display 6.3 Class With a Member Function (3 of 4) ch 7-1 - 13

Display 6.3 Class With a Member Function (4 of 4) ch 7-1 - 14

Dot (.) operator and Scope Resolution (::) Operator Used to specify "of what thing" they are members Dot operator (.) : Specifies member of particular object Scope resolution operator (::) Specifies what class the function definition comes from class DayOfYear { public: // access specifier void output(); // member function int month; // data member int day; // data member }; DayOfYear today; today.year = 2014; today.month = 5; DayOfYear::output() { } ch 7-1 - 15

A Class s Place Class is full-fledged type! Just like data types int, double, etc. Can have variables of a class type We simply call them "objects" Can have parameters of a class type Pass-by-value Pass-by-reference Can use class type like any other type! ch 7-1 - 16

Encapsulation Any data type includes Data (range of data) Operations (that can be performed on data) Example: int data type has: Data: +-32,767 Operations: +,-,*,/,%, logical, etc. Same with classes But WE specify data, and the operations to be allowed on our data! ch 7-1 - 17

Abstract Data Type (ADT) "Abstract" Programmers don t know details Abbreviated "ADT" Collection of data values together with set of basic operations defined for the values ADT s often "language-independent" We implement ADT s in C++ with classes C++ class "defines" the ADT Other languages implement ADT s as well ch 7-1 - 18

Encapsulation More on Encapsulation Means "bringing together as one" Declare a class get an object Object is "encapsulation" of Data values (attributes) Operations on the data (member functions) ch 7-1 - 19

Encapsulation Principles of OOP Bring together data and operations, but keep "details" hidden Information Hiding Details of its implementations and its operations work not known to "user" of class Data Abstraction Details of how data is manipulated within ADT/class not known to user ch 7-1 - 20

Encapsulation in Object Encapsulation and protection of private data Object outside program interface to outside Friend Functions - cin >> // standard input - cout << // standard output Public Member Functions - get() // read with validity check - set() // write with validity check Private Member Functions - house keeping Private Data Members ch 7-1 - 21

Public and Private Members Data in class almost always designated private in definition! Upholds principles of OOP Hide data from user Allow manipulation only via operations Which are member functions Public items (usually member functions) are "user-accessible" ch 7-1 - 22

Public and Private Example Modify previous example: class DayOfYear { public: void input(); void output(); private: int month; int day; }; Data now private Objects have no direct access ch 7-1 - 23

Public and Private Example 2 Given previous example Declare object: DayOfYear today; Object today can ONLY access public members cin >> today.month; // NOT ALLOWED! cout << today.day; // NOT ALLOWED! Must instead call public operations: today.input(); today.output(); ch 7-1 - 24

Public and Private Style Typically place public first Allows easy viewing of portions that can be USED by programmers using the class Private data is "hidden", so irrelevant to users Can mix and match public and private Outside of class definition, cannot change (or even access) private data ch 7-1 - 25

Accessor and Mutator Functions Object needs to "do something" with its data Accessor member functions Allow object to read data Also called "get member functions" Simple retrieval of member data Mutator member functions Allow object to change data Manipulated based on application Set member functions ch 7-1 - 26

// Display 6.4 Class with Private Members #include <iostream> #include <cstdlib> using namespace std; class DayOfYear { public: void input( ); void output( ); void set(int newmonth, int newday); //Precondition: newmonth and newday form a possible date. void set(int newmonth); //Precondition: 1 <= newmonth <= 12 //Postcondition: The date is set to the first day of the given month. int getmonthnumber( ); //Returns 1 for January, 2 for February, etc. int getday( ); private: int month; int day; }; ch 7-1 - 27

int main( ) { DayOfYear today, bachbirthday; cout << "Enter today's date: n"; today.input( ); cout << "Today's date is "; today.output( ); cout << endl; bachbirthday.set(3, 21); cout << "J. S. Bach's birthday is "; bachbirthday.output( ); cout << endl; if ( today.getmonthnumber( ) == bachbirthday.getmonthnumber( ) && today.getday( ) == bachbirthday.getday( ) ) cout << "Happy Birthday Johann Sebastian! n"; else cout << "Happy Unbirthday Johann Sebastian! n"; } return 0; ch 7-1 - 28

//Uses iostream and cstdlib: void DayOfYear::set(int newmonth, int newday) { if ((newmonth >= 1) && (newmonth <= 12)) month = newmonth; else { cout << "Illegal month value! Program aborted. n"; exit(1); } if ((newday >= 1) && (newday <= 31)) day = newday; else { cout << "Illegal day value! Program aborted. n"; } } exit(1); //Uses iostream and cstdlib: void DayOfYear::set(int newmonth) { if ((newmonth >= 1) && (newmonth <= 12)) month = newmonth; else { cout << "Illegal month value! Program aborted. n"; } exit(1); } day = 1; ch 7-1 - 29

int DayOfYear::getMonthNumber( ) { return month; } int DayOfYear::getDay( ) { return day; } //Uses iostream and cstdlib: void DayOfYear::input( ) { cout << "Enter the month as a number: "; cin >> month; cout << "Enter the day of the month: "; cin >> day; if ((month < 1) (month > 12) (day < 1) (day > 31)) { cout << "Illegal date! Program aborted. n"; exit(1); } } ch 7-1 - 30

void DayOfYear::output( ) { switch (month) { case 1: cout << "January "; break; case 2: cout << "February "; break; case 3: cout << "March "; break; case 4: cout << "April "; break; case 5: cout << "May "; break; case 6: cout << "June "; break; case 7: cout << "July "; break; case 8: cout << "August "; break; case 9: cout << "September "; break; case 10: cout << "October "; break; case 11: cout << "November "; break; case 12: cout << "December "; break; default: cout << "Error in DayOfYear::output. Contact software vendor."; } // end switch } cout << day; ch 7-1 - 31

Separation of Interface and Implementation User of class need not see details of how class is implemented Principle of OOP encapsulation User only needs "rules" Called "interface" for the class In C++ public member functions and associated comments Implementation of class is hidden Member function definitions elsewhere User need not see them ch 7-1 - 32

Structures Typically all members public No member functions Structures vs. Classes Classes Typically all data members private Interface member functions public Technically, same Perceptionally, very different mechanisms ch 7-1 - 33

Thinking Objects Focus for programming changes Before algorithms center stage Object-Oriented Programming (OOP) data is focus Algorithms still exist They simply focus on their data Are "made" to "fit" the data Designing software solution Define variety of objects and how they interact ch 7-1 - 34

Summary 7-1-1 Structure is collection of different types Class used to combine data and functions into single unit -> object Member variables and member functions Can be public accessed outside class Can be private accessed only in a member function s definition Class and structure types can be formal parameters to functions ch 7-1 - 35

C++ class definition Summary 7-1-2 Should separate two key parts Interface: what user needs Implementation: details of how class works ch 7-1 - 36

Homework 7-1 7-1.1 Structure of planets in the solar system. Each planet has following information: Name : a character string of less than 10 characters Relative-Mass : double type value of mass relative to Earth Distance from sun : double type value of mean distance from sun in [10 6 Km] 1) Design a structure for a planet with the information of planets. struct Planet { char name[10]; double relativemass; double distance; }; ch 7-1 - 37

2) Using the structure designed above, make an array Planet solar_planet[9], and initialize the array from an input file solar_planet.dat which contains following data : Name of Planet Relative Mass Distance from Sun Mercury 0.0558 57.9 Venus 0.815 108 Earth 1.0 150 Mars 0.107 228 Jupiter 318 778 Saturn 95.1 1430 Uranus 14.5 2870 Neptune 17.2 4500 Pluto 0.11 5900 3) Using the solar_planet[ ] array, make a sorted list of solar planets in non-decreasing order of relative mass. Output the result to sortedsolarplanet.dat in the same format of input file. 4) Using the solar_planet[ ] array, make a sorted list of solar planets in non-decreasing order of distance from Sun. Output the result to sortedsolarplanet.dat in the same format of input file. 5) Using the solar_planet[ ] array, make a sorted list of solar planets in non-decreasing order of name of planet. Output the result to sortedsolarplanet.dat in the same format of input file. ch 7-1 - 38

7-1.2 Write a header file Class_Planet.h with a class Planet with following members: (1) Private Data members:. name: a character string of less than 10 characters. relativemass: double type value of mass relative to Earth. distance: double type value of mean distance from sun in [10 6 Km] (2) Public methods:. constructor: constructs the object instance of Planet with given arguments. destructor: destructs the object instance of Planet. print(): printout the name, relative mass and distance of the planet object. setname(): set name that truncate the name if the length is longer than 10 characters. setrelmass(): set relative mass when the passed value is greater than 0 and less than 100; otherwise the value is set to 0. setdist(): set distance when the passed value is greater than 0 and less than 10,000.. getname(): returns the name of the planet. getrelmass(): returns the relative distance. getdistance(): returns the distance ch 7-1 - 39

7-1.3 Write a header file SolarSystem.h that includes Class_Planet.h and contains a class SolarSystem with following members: (1) Private Data members:. planets: array of planet object instances (2) Public methods:. constructor: constructs the object instance of SolarSystem. destructor: destructs the object instance of SolarSystem. addplanet: create a new planet with given parameters for the planet. deleteplanet: delete a planet with the given planet name. sortplanetsbyname(): sort the planets in the solar system in the nondecreasing order of name. sortbyrelmass(): sort the planets in the solar system in the nondecreasing order of relative mass. sortbydistance():sort the planets in the solar system in the nondecreasing order of distance. print(): print outs the ordered list of planets in the solar system ch 7-1 - 40

7-1.4 Write a solarsystem.cpp that includes the header file Class_Planet.h and solarsystem.h. (1) This program reads in solarsystem.dat file to create & initialize the solar system. (2) It prints out the sorted list of planets in the solar system: i) in non-decreasing order of name, ii) in non-decreasing order of relative mass, iii) in non-decreasing order of distance. (3) Contents of solarsystem.dat file Name of Planet Relative Mass Distance from Sun Mercury 0.0558 57.9 Venus 0.815 108 Earth 1.0 150 Mars 0.107 228 Jupiter 318 778 Saturn 95.1 1430 Uranus 14.5 2870 Neptune 17.2 4500 Pluto 0.11 5900 ch 7-1 - 41