CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Announcements HW1 grades are announced at SUCourse You may see Belal Amro at his office hour for homework grades at FENS 2014 on Wednesday 10:40-12:30.
Object-Oriented Programming in C++
Course websites CS201 page link at my website: Lecture slides Assistant’s Information Recitations Office Hours Make-up.
1 C++ Syntax and Semantics, and the Program Development Process.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Summary of what we learned last week Classes How to use classes/objects Header (.h) and implementation (.cpp) files String class Member functions: length,
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l Homework 5 ä Due this Wednesday (November 17), 19:00 l Common Problems and Questions.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
Announcements HW2 is due on Wednesday this week. HW3 will be assigned this week, will be due next week.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter 9: Value-Returning Functions
Chapter 7: User-Defined Functions II
Separate Compilation and Namespaces
Announcements General rules about homeworks
Announcements General rules about homeworks
6 Chapter Functions.
Introduction to Classes and Objects
Lab 1 Introduction to C++.
Announcements Homework 1 will be assigned this week,
Announcements HW2 is due on Wednesday this week.
Announcements General rules about homeworks
Functions Imran Rashid CTO at ManiWeber Technologies.
SPL – PS1 Introduction to C++.
Presentation transcript:

CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside of functions) prohibited ä No abrupt program termination in the middle of the program. ä Modularity and code duplication are important Code duplication must avoided l About HW2 ä Use of functions Proposed functions are just one set of possible function use in such a program If you want to use other set of functions, you should be able to demonstrate understanding of modularity and you should be able to avoid code duplication l Midterm 1 ä November 25, Saturday 10:40 – 12:30 ä Objections now, or keep quiet forever :) l Midterm 2 ä December 22, Friday, 17:40 – 19:30

CS201 – Introduction to Computing – Sabancı University 2 Chapter 3 - Continued l Overview of functions ä sequence of statements with its own local variables ä supports modularity, reduces code duplication l Data transfer between function to be called and caller function ä by means of parameters ä currently one-way from caller function into function to be called ä later we will see how to return data back to the caller function

CS201 – Introduction to Computing – Sabancı University 3 Function Prototype (from 2.6) l Functions definition has two parts ä function heading name, parameters, return type ä function body (local variables and statements within curly brackets) void display (string name) { cout << “Hello ” << name << endl; } l Like variables, a function must be declared before its first call ä Problem of function declaration order You cannot call a function before you declare it l SOLUTION: You may define function prototypes (a copy of the heading) at the beginning without function bodies

CS201 – Introduction to Computing – Sabancı University 4 Function Prototype – Example Problem l What is the problem below (program order.cpp) ? void Hi (string name) { cout << "Hi " << name << endl; Greetings(); } void Greetings() { cout << "Things are happening inside this computer" << endl; } int main() { Hi("Fred"); return 0; } Greetings() is called in Hi() but it is declared afterwards

CS201 – Introduction to Computing – Sabancı University 5 Function Prototype – Solution l Add function prototypes to the beginning (order2.cpp) #include #include using namespace std; void Hi(string); void Greetings(); void Hi (string name) { cout << "Hi " << name << endl; Greetings(); } void Greetings() { cout << "Things are happening inside this computer" << endl; } int main() { Hi("Fred"); return 0; } Prototypes Functi on Declar ations

CS201 – Introduction to Computing – Sabancı University 6 Function Prototypes l !!!Do not forget semicolon after the prototype definition!!! ä no semicolon after the parameters in normal definition l Sometimes prototypes are not necessary ä if the order of function calls allows ä But it is a good programming practice to have them In #include d files ä we have the functions’ prototypes only ä implementations of function bodies are in libraries or in other cpp files they are linked together

CS201 – Introduction to Computing – Sabancı University 7 Enumerated Types l Section l You can define your own type by giving its constant values (literals) as identifiers ä type for CardSuit ä type for colors l Type definition syntax enum TypeName { list of literals separated by comma }; l Type definition example enum CardSuit {spade, heart, diamond, club}; l You can define variables of enum types, you can use them as parameters and return types

CS201 – Introduction to Computing – Sabancı University 8 Enum types l Example use CardSuit c; c = club; l Each constant of an enum type has an associated integer code ä starting from 0 ä spade is 0, heart is 1, diamond is 2, club is 3 l Displaying an enum type variable actually displays its integer code cout << c; // displays 3 l Cannot assign an integer to an enum variable c = 2; //illegal c = CardSuit(2); //legal, c becomes diamond l cannot input cin >> c; //invalid l can use comparison operators (, = operators compare codes) if (c == heart)

CS201 – Introduction to Computing – Sabancı University 9 Introduction to Classes and Objects (3.4) l In object-oriented programming terminology, a class is defined as a kind of programmer-defined type l From the natural language definition of the word “class”: ä Collection of members that share certain attributes and functionality ä Likewise classes in object-oriented programming l In object oriented programming languages (like C++) classes are used to combine everything for a concept (like date, student) ä Data (e.g. student id, gpa) ä Functions (e.g. students enroll, students graduate)

CS201 – Introduction to Computing – Sabancı University 10 Introduction to Classes and Objects We define variables of types (like int, double ). Similarly, we define objects of classes ä an object is a member of a class l Why classes and objects? In other words, why object- oriented programming? ä It gives programmers the ability to write programs using off-the-shelf components without dealing with the complexity of those components ä Saves time and effort l You may design and implement, and later use your own classes, but we will start with using other-programmers- defined classes ä this is what a programmer generally does

CS201 – Introduction to Computing – Sabancı University 11 How to Use Classes? l The behavior of a class is defined by member functions (methods) by which objects of that class are manipulated l You should know about the member functions and what they do ä name of the function ä parameters and parameter types ä return type ä functionality l You don’t need to know how the function is implemented  analogy: you can add two int variables using +, but you don’t need to know how computer really adds ä more analogy: you can drive cars, but you don’t need to know how the fuel injection works

CS201 – Introduction to Computing – Sabancı University 12 Example: Robots Class (not in the book) l A class for robots l You can create robots (objects) at different locations and facing different orientations (east, west, south or north) ä “constructor”: general name for object creating functions l You can change the color of the robot; color is parameter  SetColor member function l Robots can turn right  TurnRight member function ä no parameter l Robots can move at the facing direction  Move member function ä can be used with or without parameters without parameter: 1 step with parameter: parameter is number of steps l more robot functions are later

CS201 – Introduction to Computing – Sabancı University 13 Robot World l Robots live on a world of cells ä each cell has a coordinate ä southwest is (0,0) point ä south and west bounded ä east and north unbounded ä no cells with negative coordinates

CS201 – Introduction to Computing – Sabancı University 14 More on robots class and robot world l Robot world also allows you to ä install/uninstall barriers at cell boundaries ä plant/remove “things” within cells ä save, save as, open, run program, etc. (utilities) l Robot world is actually a Windows application ä it needs two files to be added up to the project robots.cpp (robot class and other utilities are implemented) miniFW.cpp (for windows programming – out of scope of this course) The file in which you write your main program should be another separate file. robots.h is to be #included at the beginning of the main program robots.cpp, miniFW.cpp, robots.h and miniFW.h files should be in the folder as your actual program file. project should be win32 application – This is very important! In such a project, robot world is created automatically even if you do not have anything in main. l When “run” clicked, program is executed on the current robot world. Important Detail: your main is not actually the main program; actual main ( WinMain ) is in robots.cpp, but do not bother with this detail for now. Caution: cin and cout does not work in robot world

CS201 – Introduction to Computing – Sabancı University 15 simplerobot.cpp – sample program that utilizes robots class #include "Robots.h" //simple robot test program int main () { Robot Ali(5, 1); //Ali is a robot at (5,1) location and facing east Ali.SetColor(white); //Ali's color is set to white Robot Ayse(5, 8, north);//Ayse is a robot at (5,8) location and facing north Ayse.SetColor(red); //Ayse's color is set to red Ali.Move(5); Ayse.TurnRight(); Ayse.Move(); Ayse.TurnRight(); Ayse.Move(10); Ali.TurnRight(); Ali.Move(4); return 0; }

CS201 – Introduction to Computing – Sabancı University 16 Where is a Class Defined? l Class Interface/definition (member function prototypes and and some other declarations) is in a header file (.h file) ä function prototype includes function name, return type and parameters. Function body is not there. ä a function’s prototype is its definition. It allows the program to call that function. ä Prototype definitions are generally used for library functions. Function body is not known, but its interface must be known by the program in order to call that function. ä Prototype definitions can be used for user-defined functions too l Implementations of the member functions are in a.cpp file l Robot example ä class interface is in robots.h that is why it is included in simplerobot.cpp ä class implementation is in robots.cpp part of the project – linked together

CS201 – Introduction to Computing – Sabancı University 17 robots.h - Definition of class robots (partial) #ifndef Robots_h // to avoid duplicate inclusions of robots.h #define Robots_h // enumerated types for colors and directions enum Direction { east, west, north, south }; enum Color { white, yellow, red, blue, green, purple, pink, orange }; class Robot { public: Robot (int x, int y, Direction dir = east, int things = 0); // robot constructor - color yellow, default direction is east, default //things in bag is zero void Move (int distance = 1); // to move robot, default displacement is 1 void TurnRight (); // to turn the robot right void SetColor (Color color); //to change the color of robot // there are some other functions that we will see later // see next page for the rest of the file

CS201 – Introduction to Computing – Sabancı University 18 robots.h - Definition of class robots (partial) private: int xPos; //x-coordinate of the robot int yPos; //y-coordinate of the robot Direction direction; //direction of the robot Color color; //color of the robot int bag; //number of things in the bag of the robot bool stalled; //is the robot dead? bool visible; //is the robot visible on the screen? //the rest of the private part is out of scope of this course, at least for now }; #endif

CS201 – Introduction to Computing – Sabancı University 19 Parts of Class Definition l Public ä Member functions as seen by programmer ä Programmer can use the functions defined in the public section only ä Constructors special member function to create objects (variables) there might be several constructors with same name, but different parameters (not the case for Robot class) l Private ä Necessary for internal implementation of class e.g. xPos, yPos – used by Move ä Not accessible by programmer e.g. in simplerobot.cpp, programmer cannot modify xPos

CS201 – Introduction to Computing – Sabancı University 20 How to l How to define objects? class_name object_name_list_separated_by_comma ; ä do not forget arguments for each object, if any. l How to call a member function? object_name. function_name ( arguments ); ä a member function operates on an object for which it is called.

CS201 – Introduction to Computing – Sabancı University 21 How to l How to use Robot class as a parameter ä if you do not change the color, position, orientation etc. of the robot, then use as other types (at least for now – later we will see more efficient ways) void dothis (Robot myrobot, int param)  However, if you change the robot’s characteristics (color, position, orientation, etc.), then you have to use the character & between Robot and the parameter name void Go (Robot & myrobot, int x, int y) ä Calling such functions is not different Do not use & while calling Robot rob(5, 6, west); Go (rob, 12, 5); We will see the & notation in more detail later (Section 6.2.3) ä this type of parameters is called “reference parameters” Recommended since you generally change the robot characteristics in functions

CS201 – Introduction to Computing – Sabancı University 22 Some more recommendations l Avoid creating robots in user-defined functions ä Create all necessary robots in main ä If needed pass them as parameters to other functions l Addition to scope rules ä IMPORTANT RULE: An identifier (e.g. an object or a variable) can be referred only in the compound block in which it is declared ä A compound block is the statements and declarations within matching curly brackets e.g. after if or else ä Implication of this rule in robot programs: when a robot object is created in a compound block, it can be referred only in that block Otherwise, undeclared identifier error occurs Solving this problem by re-creating it is NOT A SOLUTION if (x>0) { Robot r(x, 0); r.Move(3); } r.Move(); Undeclared identifier

CS201 – Introduction to Computing – Sabancı University 23 Compiling, Linking l Single file case l Linking is necessary to use the libraries ä for example, iostream for cin and cout, string for string class operations  library functions are defined (prototypes) in header files ( #include d) ä library function bodies are ready in object code linked myprog.cpp (source code) myprog.obj (object code) compile myprog.exe link

CS201 – Introduction to Computing – Sabancı University 24 Compiling, Linking l several.cpp files ä user-defined class implementations and some utility functions can be written in different.cpp files ä those files are independently compiled and then linked together to create the executable code libraries are linked too int main () { Robot Ali(5, 1); Ali.SetColor(white); Ali.Move(5); return 0; } simplerobot.cpp Robot::Robot (int x, int y, { xPos = x; yPos = y; direction = dir; color = yellow;... robots.cpp simplerobot.obj robots.obj libraries

CS201 – Introduction to Computing – Sabancı University 25 #include l Kind of copy-paste ä specified header file is copied before compilation l Include file locations ä standard ones are in INCLUDE directory under....\Microsoft Visual Studio\VC98 ä Tools  Options  Directories can specify more directories to search for header files l difference between ä #include only search in directories specified in options mostly used for standard header files like iostream ä #include “filename” first search in the local directory, then the ones in options for user defined header files

CS201 – Introduction to Computing – Sabancı University 26 Adding Files to Projects in VC++ l.cpp files that are compiled and linked together (like class implementations) must be added to the project ä otherwise link error l Standard libraries are found and linked automatically ä no need to add anything for them l User-defined libraries, if available in object code (e.g..lib files), must be added to the project ä otherwise link error l Header files may or may not be added in project ä even added, the compiler still needs to find them in a folder they may not be found if directory settings are wrong ä if not added, they are shown as “external dependencies”