Summary of what we learned last week Classes How to use classes/objects Header (.h) and implementation (.cpp) files String class Member functions: length,

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 Functions.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
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.
Guide To UNIX Using Linux Third Edition
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.
Pointer Data Type and Pointer Variables
Announcements Midterm is TOMORROW! On August 2 nd Tuesday at 19:40 (~ 100 minutes) in FENS L045 Today at 14:30-17:30 there is an extra recitation in FENS.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside.
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.
Separate Compilation. A key concept in programming  Two kinds of languages, compilation (C, Pascal, …) and interpretation (Lisp, …, Matlab, Phython,
The Structure of a C++ Program. Outline 1. Separate Compilation 2. The # Preprocessor 3. Declarations and Definitions 4. Organizing Decls & Defs into.
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.
Object-Oriented Programming in C++
Announcements Final NEXT WEEK (August 13 th Thursday at 16:00) Recitations will be held on August 12 th Wednesday We will solve sample final questions.
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
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 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Announcements Midterm1 is on this Tuesday at 19:40. Classrooms as follows: if (LastName
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
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.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
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.
1 Introduction to Object Oriented Programming Chapter 10.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l Homework 5 ä Due this Wednesday (November 17), 19:00 l Common Problems and Questions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
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.
Chapter 9: Value-Returning Functions
Chapter 7: User-Defined Functions II
Announcements Homework 5 – Robot game will be assigned this week
Announcements Homework 5 – Robot game will be assigned this week
Chapter 5 Classes.
Announcements Homework 3 – Robot game will be assigned this Friday
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Announcements Homework 5 – Robot game will be assigned this week
Separate Compilation and Namespaces
Introduction to Classes
Introduction to Classes and Objects
Announcements HW2 is due on Wednesday this week.
SPL – PS1 Introduction to C++.
Presentation transcript:

Summary of what we learned last week Classes How to use classes/objects Header (.h) and implementation (.cpp) files String class Member functions: length, substr, find/rfind Loops Today’s topics Classes How to use classes/objects Header (.h) and implementation (.cpp) files Robot class

You can use enum type when you want to define all the possible values for your type type for CardSuit type for colors Type definition syntax enum TypeName {list of literals separated by comma}; Type definition example enum CardSuit {spade, heart, diamond, club}; You can define variables of enum types, you can use them as parameters and return types throughout the cpp file An enum type must be defined at global level (after using namespace std; and before the function declarations) Enumerated Types ( Section 9.3.4)

Enum types Example use enum CardSuit {spade, heart, diamond, club}; CardSuit c; c = club; 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 Displaying an enum type variable actually displays its integer code cout << c; // displays 3 Cannot assign an integer to an enum variable c = 2; // illegal c = CardSuit(2); // legal, c becomes diamond Cannot input into an enum cin >> c; // invalid Can use comparison operators (, = operators compare codes) if (c <= heart) cout << "hi" << endl;

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

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 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 Objects are how real-world entities are represented. 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

How to Use Classes? The behavior of a class is defined by its member functions (methods) by which objects of that class are manipulated You should know about the member functions and what they do name of the function parameters and parameter types return type functionality 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

Example: Robots Class (not in the book) A class for robots You can create robots (objects) at different locations and facing different orientations (east, west, south or north) “constructor”: general name for object creating functions You can change the color of the robot; color is parameter SetColor member function Robots can turn right TurnRight member function no parameter 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 There are more robot functions, let’s use these first

Robot World 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

More on robots class and robot world 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) Robot world is actually a Windows application it needs two files to be added 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 a 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. 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 ignore this detail for now. Caution: cin and cout do not work in robot world

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; }

Where is a Class Defined? Class definition/interface (member function prototypes 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 Implementations of the member functions are in a.cpp file Robot example class definition/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

robots.h - Definition of class Robot (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

robots.h - Definition of class Robot (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

Parts of Class Definition 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) Private Mostly the data part of the class 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

How to define objects? class_name object_name_list_separated_by_comma; do not forget arguments for each object, if any. How to call a member function? object_name.function_name(arguments); a member function operates on an object for which it is called. How to

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 the function 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 are called “reference parameters” Recommended since you generally change the robot characteristics in functions

Some more recommendations Avoid creating robots in user-defined functions Create all necessary robots in main If needed pass them as parameters to other functions 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

Example using robot class (see rectangularscan.cpp) Write a program in which the robot starts at 0,0 and searches a rectangular space that covers n*n cells n is input (in the example below, n is 8) during this journey the robot should pick or put things on the cells so that all visited cells occupy one thing

Compiling, Linking Single file case Linking is necessary to use the libraries Examples: iostream for cin and cout, string for string class operations Library functions are defined (prototypes) in header files (#included) library function bodies are ready in object code linked myprog.cpp (source code) myprog.obj (object code) compile myprog.exe link

Compiling, Linking 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

#include Kind of copy-paste specified header file is copied before compilation Include file locations standard ones are in INCLUDE directory under …\Microsoft Visual Studio 9.0\VC\include Tools  Options  Projects and Solutions  VC++ Directories can specify more directories to search for header files 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

Adding Files to Projects in VC++.cpp files that are compiled and linked together (like class implementations) must be added to the project otherwise link error Standard libraries are found and linked automatically no need to add anything for them User-defined libraries, if available in object code (e.g..lib files), must be added to the project otherwise link error Header files may or may not be added in project if not added, they are shown as “external dependencies” and this is OK No matter added to the project or not, the compiler still needs to find the header files in a folder they may not be found if directory settings are wrong, so be careful!

Functions that return values from the Robot Class Robot class has several member functions Move, TurnRight and SetColor are void functions Robot class also has member functions that return values. Some are below: bool Blocked () is the robot blocked? bool FacingEast () is the robot facing east? See RobotWorld.pdf file for the complete list of those functions.

Free functions and member functions The functions in are free functions, they aren’t part of a class C++ is a hybrid language, some functions belong to a class, others do not Java and C# are pure object-oriented languages, every function belongs to a class Similarly, IsLeapYear is also a free function Actually any function that does not operate on an object is a free function However, Move, TurnRight are functions for Robot class they are not free, they operate on robots only that is why they are called member functions all robot functions are member functions

RandGen Class A Tapestry class for random number generation Add randgen.cpp to your project and have #include "randgen.h" in your program Four member functions int RandInt(int max = INT_MAX); returns a random integer in [0..max) int RandInt(int low, int max); returns a random integer in [low..max] double RandReal(); returns a random double value in [0..1) double RandReal(double low, double max); returns a random double value in the range of [low..max] see numberguess.cpp for an example program that use RandGen

Overloading In RandGen class, there are two different functions named RandInt so as RandReal Using the same name for more than one function is called overloading. They are differentiated by parameter types Return types do not differentiate funtions All member and free functions can be overloaded.

Implementation of Robot Class - 1 Your next homework will be about updating the Robot class you will add some new member functions that requires to deal with robots.h and robots.cpp files (actually in the homework, you will use an updated class for which the file names are robots_modified.h and robots_modified.cpp) and you will use those newly added functions in an application It is a good idea to have a look at how this class is implemented It is designed and implemented by Ersin Karabudak We have made some changes later Robot class implementation is quite complex Robot, RobotWindow and RobotWorld are different structures we will not deal with RobotWindow and RobotWorld, but the implementation file contains robot class implementation and the details of RobotWindow and RobotWorld too. Do not get confused. Robots are maintained as a circular doubly linked list it is a data structure that uses pointers (probably will see in CS300) but do not get thrilled! you will not need those complex structures for the member functions that you will add. Some details you have to know will be given now and more details will be given in recitations this week

Implementation of Robot Class - 2 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 (); void Move (int distance = 1); bool Blocked (); void TurnRight (); bool PickThing (); bool PutThing (); void SetColor (Color color); bool FacingEast (); bool FacingWall (); bool CellEmpty (); bool BagEmpty (); constructor Destructor (not needed in HW5) member functions continued on the next slide

Implementation of Robot Class - 3 private: int xPos; //x coordinate of the location of robot int yPos; //y coordinate of the location of robot Direction direction; //current direction of robot Color color; //current color of robot int bag; //current # of things in the bag of robot bool stalled; //true if the robot is dead bool visible; //true if the robot is visible Robot *next; Robot *prev; static Robot *list; friend struct RobotWindow; }; Private Data pointers for the data structure you will not need them RobotWindow may refer Robot’s private data

Implementation of Robot Class - 4 Previous two slides were in the robots.h (now robots_modified.h). Now let’s go over the robots.cpp (now robots_modified.cpp) file in VC++ environment In the next homework, you are going to add 6-8 member functions to the robot class Some of the member functions will be done in recitations this week Hints try to use currently available member functions e.g. for PickThings, try to use PickThing in a loop rather than writing some thing similar to PickThing do not hesitate to modify or access private data members when needed e.g. you will need such an update for TurnFace function if you change the state of a robot within the current cell, use the following to update the window theRobotWindow->Redraw(this);

Implementation of Robot Class - 5 Hints for the next homework (cont’d) you will need to use the function called IsPressed defined in miniFW.h (it is going to be renamed as miniFW_modified.h) so include this header file to your main program file this function ( IsPressed ) is to check whether a key (e.g. an arrow key) is pressed or not - details are in recitations Some other changes in the Robot World and Robot Class If a robot hits another robot, both die! No automatic message is displayed when a robot dies Now the bag content is written in robots (if not zero) Use robots_modified.h, robots_modified.cpp, miniFW_modified.h and miniFW_modified.cpp files in HW4 They will be provided to you in the homework and/or recitation package

Example using robot class (see rectangularscan.cpp) Write a program in which the robot starts at 0,0 and searches a rectangular space that covers n*n cells n is input (in the example below, n is 8) during this journey the robot should pick or put things on the cells so that all visited cells occupy one thing