Programming in C/C++ Lecture 3

Similar documents
Programming in C/C Lecture 3

Chapter-10 INHERITANCE

Scroll down to New and another menu will appear. Select Folder and a new

Common Language Runtime

LAB 7 (June 29/July 4) Structures, Stream I/O, Self-referential structures (Linked list) in C

Lab 4. Name: Checked: Objectives:

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2

History of Java. VM (Java Virtual Machine) What is JVM. What it does. 1. Brief history of Java 2. Java Version History

CS5530 Mobile/Wireless Systems Swift

Relational Operators, and the If Statement. 9.1 Combined Assignments. Relational Operators (4.1) Last time we discovered combined assignments such as:

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2 Iterative Code Design handout Style Guidelines handout

COP2800 Homework #3 Assignment Spring 2013

What s New in Banner 9 Admin Pages: Differences from Banner 8 INB Forms

Assignment #5: Rootkit. ECE 650 Fall 2018

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture2 Functions

MyUni Adding Content. Date: 29 May 2014 TRIM Reference: D2013/ Version: 1

Laboratory #13: Trigger

Renewal Reminder. User Guide. Copyright 2009 Data Springs Inc. All rights reserved.

Ascii Art Capstone project in C

These tasks can now be performed by a special program called FTP clients.

6 Ways to Streamline Your Tasks in Outlook

1on1 Sales Manager Tool. User Guide

McGill University School of Computer Science COMP-206. Software Systems. Due: September 29, 2008 on WEB CT at 23:55.

Chapter 3 Stack. Books: ISRD Group New Delhi Data structure Using C

CS1150 Principles of Computer Science Methods

Municode Website Instructions

One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it.

Data Structure Interview Questions

Programming Project: Building a Web Server

TRAINING GUIDE. Overview of Lucity Spatial

Outlook Web Application (OWA) Basic Training

Project 3 Specification FAT32 File System Utility

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

Project 4: System Calls 1

Interfacing to MATLAB. You can download the interface developed in this tutorial. It exists as a collection of 3 MATLAB files.

SITEDIARY.org. User Manual PLANIUM Oy

WebEx Web Conferencing Quick Start Guide

THE ALGOL FAMILY AND ML

August 22, 2006 IPRO Tech Client Services Tip of the Day. Concordance and IPRO Camera Button / Backwards DB Link Setup

AngularJS. Unit Testing AngularJS Directives with Karma & Jasmine

Create Your Own Report Connector

The Login Page Designer

Sometimes it's necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

CSE 361S Intro to Systems Software Lab #2

MOS Access 2013 Quick Reference

DECISION CONTROL CONSTRUCTS IN JAVA

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

UML : MODELS, VIEWS, AND DIAGRAMS

INSTALLING CCRQINVOICE

Marian Online 2 Instructor Manual 12

Faculty Textbook Adoption Instructions

Populate and Extract Data from Your Database

BANNER BASICS. What is Banner? Banner Environment. My Banner. Pages. What is it? What form do you use? Steps to create a personal menu

Getting Started with DocuSign

Word 2007 The Ribbon, the Mini toolbar, and the Quick Access Toolbar

You may receive a total of two GSA graduate student grants in your entire academic career, regardless of what program you are currently enrolled in.

Course 10262A: Developing Windows Applications with Microsoft Visual Studio 2010 OVERVIEW

Preparation: Follow the instructions on the course website to install Java JDK and jgrasp on your laptop.

Integrating QuickBooks with TimePro

University Facilities

Class Roster. Curriculum Class Roster Step-By-Step Procedure

Lab 0: Compiling, Running, and Debugging

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Using SPLAY Tree s for state-full packet classification

Kaltura MediaSpace TM Enterprise 2.0 Requirements and Installation

Gmail and Google Drive for Rutherford County Master Gardeners

C++ Reference Material Programming Style Conventions

Enabling Your Personal Web Page on the SacLink

Proper Document Usage and Document Distribution. TIP! How to Use the Guide. Managing the News Page

A solution for automating desktop applications with Java skill set

Computational Methods of Scientific Programming Fall 2008

Element Creator for Enterprise Architect

Developing Java Web Services. Duration: 5 days

Type: System Enhancements ID Number: SE 93. Subject: Changes to Employee Address Screens. Date: June 29, 2012

Procurement Contract Portal. User Guide

Information about the ACC Education App Featuring ACCSAP 9

CS1150 Principles of Computer Science Introduction (Part II)

Entering an NSERC CCV: Step by Step

The following screens show some of the extra features provided by the Extended Order Entry screen:

How to use DCI Contract Alerts

Profiling & Debugging

Avaya 9610 IP Telephone End User Guide

Uploading Your Catalogue

CLIC ADMIN USER S GUIDE

Cookies: enable, disable or delete cookies

Reviewer Information Sheet for Committee Members

OpenSceneGraph Tutorial

Web of Science Institutional authored and cited papers

Adobe InDesign: The Knowledge

Element Creator for Enterprise Architect

Messing with SQL in Dataflex What is available in Dataflex 19.0 o cconnection.pkg

FIT 100. Lab 10: Creating the What s Your Sign, Dude? Application Spring 2002

Second Assignment Tutorial lecture

EASTERN ARIZONA COLLEGE Java Programming I

Life Cycle Objectives (LCO) CSE 403, Spring 2006, Alverson

- Replacement of a single statement with a sequence of statements(promotes regularity)

Managing Your Access To The Open Banking Directory How To Guide

Using CppSim to Generate Neural Network Modules in Simulink using the simulink_neural_net_gen command

Transcription:

Prgramming in C/C++ Lecture 3 http://few.vu.nl/~nsilvis/c++/2006 Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl vrije Universiteit amsterdam Object Oriented Prgramming in C++ abut bject riented prgramming (OOP) structures in C classes and bjects in C++ separate cmpilatin Prcedural prgramming the prblem is decmpsed in smaller units named prcedures and data can be assembled in packages, called structures. Data and prcedures are separated. C, Pascal, Frtran, Mdula2 are prcedural languages 1

Object riented prgramming Nwadays sftware becmes mre cmplex. Prgrams created in prcedural languages are difficult t manage, hard t maintain and expensive t extend. A new way t prgram : bject riented prgramming (OOP) OOP cmbines data and prcedures in ne single unit = bject. abut OOP Object riented prgramming is a tl fr new challenges in sftware develpment - ffers a clser fit t the way human think - imprves cmmunicatin - imprves the quality f sftware Gal : t design high quality sftware at lw cst Imprtant OOP cncepts: encapsulatin data hiding inheritance plymrphism Objects Essence f OOP: Dn t think abut data and functins separately, think abut bjects. Objects are small bundles f data which knw hw t d thing with themselves. Example: Yu can think: A car is a cllectin f wheels, drs, seats, windws. But think what a car can d: mve, speed up, slw dwn, stp, park, etc. Put everything yu knw abut a car in ne bject. Yu dn t say : the cmputer mves the car. Yu say : the car mves itself. 2

Examples f bjects a windw : clse, pen, resize, mve a data structure (list, tree): find, remve srt, insert a file: pen,clse, read,write,rename 3D bject: clr,rtate,resize Classes All cars are bjects f the same type. The descriptin f this type is a class: class Car Advantage: clients f yur class can use it withut wrrying abut hw it wrks. C has structures structure Car string name ; int tpspeed ; int capacity ; ; Car my_car, yur_car; // declare 2 variables f type Car my_car.name = Frd ; cut << my_car.name ; structure = class withut actins yur_car.name = Smart" ; yur_car.capacity = 2 ; 3

C++ has classes A class is a user-defined type. The variables f this type are bjects. A class can be btained frm a structure if sme member functins are added. Encapsulatin = cmbining a number f items (variables and functins) int a single package such an bject f a class my_ford, yur_mini are OBJECTS f type Vehicle First example with classes #include <istream> using namespace std; class Vehicle public : int weight, capacity; flat tp_speed ; vid printdata() ; ; main() Vehicle my_car ; my_car.printdata(); return 0 ; vid Vehicle::printData() cut << "weight= " << weight << " capacity = " << capacity << " Tp speed= " << tp_speed << endl; Test What is the utput f this prgram? 4

Private and public a member (variable r functin) can be private r public a "gd" class keeps its member variables private = data hiding and uses public member functins t access r change each private variable. These public member functins are called accesrs and mutatrs. accesr functin is usually named get***... mutatr functin is usually named set***.. Example: data hiding class Vehicle private: int weight, capacity; flat tpspeed ; public: vid printdata() ; //here are 3 accessr functins int getweight(); int getcapacity(); int gettpspeed(); //and nw the 3 mutatr functins int setweight (int new_weight); int setcapacity (int new_capacity); int settpspeed (flat new_tpspeed); ; Cnstructrs Definitin: A cnstructr is a special member functin autmatically called when an bject is created. Jb: Cnstructrs are used fr bjects initializatin. Rules: the cnstructrs shuld be public a cnstructr must have the same name as the class the cnstructr has n type fr the return value (nt even vid) a class can have mre than 1 cnstructr (verlading) a cnstructr withut arguments is called default cnstructr: Vehicle() if n cnstructr is declared, C++ generates a default cnstructr that des nthing OOP tip: Always include a default cnstructr. 5

Destructrs Definitin: A destructr is a special member functin called autmatically when the bject f the class passes ut f scpe (destryed) Jb: a destructr returns memry t the freestre by eliminating all dynamic variables created by the bject. Rules: has the same name as the class but begins with a tilde ~. ~Vehicle () is the destructr f the class Vehicle. has n type fr the value returned, nt even vid. a destructr has n parameters a class can have nly ne destructr OOP tip: always use a destructr if the bject creates dynamic variables Example: cnstructrs & destructrs #include <istream> using namespace std ; class Vehicle private: int weight, capacity; flat tpspeed ; public: vid printdata() ; Vehicle () ; // default cnstructr Vehicle(int new_weight, int new_cap, flat new_tpspeed) ; //anther cnstructr with 3 parameters; ~Vehicle() ; // destructr ; Example: cnstructrs & destructrs vid Vehicle::printdata() cut << "weight= " << weight << " capacity = " << capacity << " tp speed= " << tpspeed << endl ; Vehicle::Vehicle() tpspeed = weight = capacity = 0 ; cut << "Object created " << endl ; Vehicle::Vehicle (int new_weight, int new_cap, flat new_tpspeed) weight = new_weight; capacity = new_cap ; tpspeed = new_tpspeed ; cut << "bject created & initiliazed" << endl ; Vehicle::~Vehicle () cut << "Object destryed"<< endl ; 6

Example: cnstructrs & destructrs int main() Vehicle mycar1 ; Vehicle mycar2(10000,4,125) ; mycar1.printdata() ; mycar2.printdata() ; return 0 ; Gives the utput: Object created Object created & initialized weight = 0 capacity = 0 tp speed = 0 weight = 10000 capacity = 4 tp speed = 125 Object destryed Object destryed Friend functins Definitin: a friend functin f a class is an rdinary functin which has access t the private members f this class Hw t make a functin friend f a class? list its name in the class definitin by using the keywrd friend Example: friends #include <istream> using namespace std ; cnst int MAX_SIZE = 100; class TemperatureArray private: duble array[max_size]; int size; public: TemperatureArray(); // cnstructr vid add_temperature(duble temperature); bl full() ; friend vid print (cnst TemperatureArray& the_bject); ; 7

Example: friends vid print (cnst TemperatureArray& the_bject) fr (int i = 0 ; i < the_bject.size ; i++) cut << the_bject.array[i] << endl ; int main() TemperatureArray my_array ; fr (int i=1 ; i < 10 ; i++) my_array.add_temperature (i) ; print (my_array) ; return 0 ; Example friends TemperatureArray::TemperatureArray() size = 0 ; vid TemperatureArray::add_temperature (duble temperature) if (full() ) cut << "Array is full" << endl ; exit(1) ; else array[size]=temperature ; size = size + 1; bl TemperatureArray::full() return (size==max_size) ; Abstract data types Definitin: a data type is called abstract data type (ADT) if the prgrammer wh uses the type des nt have access t the details f hw the values and functins are implemented Example: C++ predefined types (int, duble, etc) and C++ peratrs. OOP tip: Make sure all the classes yu define are ADT's Hw t make yur class ADT? make all member varibales private separate the specificatin f hw the type is used by a prgrammer (= interface) frm the details f hw the type is implemented (=implementatin) 8

Separate cmpilatin A small bject-riented prgram shuld have : an interface file: usually with the extensin xxx.h - a header file that describes the services prvided by the class. an implementatin file: cntains the bdies fr the member functins, usually xxx.cpp an applicatin file, creates and uses bjects f this class, yyy.cpp Rule: Every file using the class must include the apprpriate interface file #include <libclass.h> ; < > fr system interface file, part f standard C++ library #include "myclass.h" ; " " fr immediate interface files, in the same directry as the surce cde Hw t cmpile multiple files? Optin1: Cmpiling by hand: g++ car.cpp wheels.cpp drs.cpp windws.cpp bdy.cpp car.exe Multiple files: gmake Each line in the makefile lks like this: target: which files are necessary [tab] hw t btain the target Optin 2: Use gmake utility gmake reads inf frm a makefile The makefile: car: car. wheels. drs. windws. bdy. g++ car. wheels. drs. windws. bdy. car car.: car.cpp g++ -c Wall car.cpp wheels.: wheels.cpp g++ -c Wall wheels.cpp drs.: drs.cpp g++ -c Wall drs.cpp windws.: windws.cpp g++ -c Wall windws.cpp bdy.: bdy.cpp bdy.h g++ -c Wall bdy.cpp clean: rm f *. 9

using #ifndef In rder t avid headers t be included mre than nce, C++ needs sme cnstructin t say : if yu have included this stuff befre, d nt include it again. Use this sequence in the header file: #ifndef STACK_H #define STACK_H...class definitin #endif Example multiple files: stack Prblem: write a class t implement a stack. Use this class in a prgram which reads a wrd as a sequence f letters and types this wrd in reversed rder. Use multiple files and separate cmpilatin. The interface file: stack.h #ifndef STACK_H #define STACK_H struct StackNde char data; StackNde *next ; ; typedef StackNde* StackNdePtr; class Stack private: StackNdePtr tp ; public: Stack() ; ~Stack() ; vid push(char the_symbl); char pp() ; bl empty() ; ; #endif 10

Implementatin file: stack.cpp (1/2) #include <istream> #include <cstddef> #include stack.h using namespace std; Stack::Stack() tp = NULL ; Stack::~Stack() char char_crt ; while (!empty()) char_crt = pp() ; //pp calls delete bl Stack::empty() return (tp==null) ; Implementatin file:stack.cpp (2/2) vid Stack::push (char the_symbl) StackNdePtr temp_ptr ; temp_ptr = new StackNde ; temp_ptr->data = the symbl ; temp_ptr->next = tp ; tp = temp_ptr ; char Stack::pp() if (empty ()) cut << Errr: ppping an empty stack.\n"; exit (1) ; char result = tp->data ; StackNdePtr temp_ptr ; temp_ptr = tp ; tp = tp->next ; delete temp_ptr ; return result ; Applicatin prgram: test.cpp #include <istream> #include "stack.h" using namespace std; int main() Stack s ; char next_char, ans ; d cut << "Enter a wrd: "; cin.get (next_char) ; while (next_char!= '\n') s.push(next_char); cin.get(next_char) ; cut << "Written backward is: "; while (!s.empty()) cut << s.pp() ; cut << endl ; cut << "Again?(y/n):" ; cin >> ans ; cin.ignre (10000, '\n'); while (ans!= 'n' && ans!= 'N'); return 0 ; Output: Enter a wrd: bicycle Written backward is: elcycib Again?(y/n): n 11