Title: Announcements
1Announcements
- 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
- Common Submission Mistakes
- In HW1, some students submitted empty/wrong files
- Make sure that you send the cpp file otherwise
we cannot grade - rar format is not allowed for compression please
use zip - Do not use blanks, Turkish characters, special
symbols in the filenames - Only English alphabet letters, digits and
underscore are allowed - Please submit the required files only, not the
entire project folder - 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 - Midterm 1 November 22, Saturday 1040 1220
- Midterm 2 December 26, Friday, 1740 1920
2Chapter 3 - Continued
- Overview of functions
- sequence of statements with its own local
variables - supports modularity, reduces code duplication
- 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
3Function Prototype (from 2.6)
- 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 ltlt Hello ltlt name ltlt endl
-
- 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
- SOLUTION You may define function prototypes (a
copy of the heading) at the beginning without
function declarations
4Function Prototype Example Problem
- What is the problem below (program order.cpp) ?
- void Hi (string name) cout ltlt "Hi " ltlt
name ltlt endl Greetings()void
Greetings() cout ltlt "Things are happening
inside this computer" ltlt endlint main()
Hi("Fred") return 0 - Greetings() is called in Hi() but it is declared
afterwards
5Function Prototype Solution
- Add function prototypes to the beginning
(order2.cpp) - include ltiostreamgtinclude ltstringgtusing
namespace stdvoid Hi (string)void
Greetings()void Hi (string name) cout ltlt
"Hi " ltlt name ltlt endl Greetings()void
Greetings() cout ltlt "Things are happening
inside this computer" ltlt endlint main()
Hi("Fred") return 0
Prototypes
Function Declarations
6Function Prototypes
- !!!Do not forget semicolon after the prototype
definition!!! - no semicolon after the parameters in normal
definition - Sometimes prototypes are not necessary
- if the order of function calls allows
- But it is a good programming practice to have
them - Parameter names are not needed in prototypes
- But it is OK if you have the parameter names.
- In included files
- we have the functions prototypes only
- implementations of function bodies are in
libraries or in other cpp files - they are linked together
7Enumerated Types
- Section 9.3.4
- You can define your own type by giving its
constant values (literals) as identifiers - 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 - So an enum type must be defined as global (after
using namespace std and before the function
declarations) - Such a global type declaration is not a
prohibited use of globals.
8Enum types
- Example use
- 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 ltlt c // displays 3
- Cannot assign an integer to an enum variable
- c 2 //illegal
- c CardSuit(2) //legal, c becomes diamond
- cannot input
- cin gtgt c //invalid
- can use comparison operators (lt, gt, lt, gt, ,
!) - The relational operators lt, gt, lt, gt compare
codes - if (c lt heart)
- cout ltlt "hi" ltlt endl
9Introduction 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 (e.g. student id, gpa)
- Functions (e.g. students enroll, students
graduate)
10Introduction 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
- 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
11How to Use Classes?
- The behavior of a class is defined by 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 dont need to know how the function is
implemented - analogy you can add two int variables using ,
but you dont need to know how computer really
adds - more analogy you can drive cars, but you dont
need to know how the fuel injection works
12Example Robot 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) - We use constructor for this purpose
- constructor general name for object creating
functions - You can change the color of the robot color is
parameter of an enumerated type - 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
- more robot functions will be given later
13Robot 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
14More 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 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. - When run clicked, your 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 do not work in robot world
15simplerobot.cpp sample program that utilizes
robots class
- include "Robots.h"
- using namespace std
- //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.Move()
- Ayse.TurnRight()
- Ayse.Move(10)
- Ali.TurnRight()
- Ali.TurnRight()
16Where is a Class Defined?
- Class definition/interface is in a header file (a
file with .h extension) - member function prototypes and and some other
declarations - function implementations are not in this header
file - 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
17robots.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
Continued on the next page
18robots.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
19Parts 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 the implementation of
Move function, but we do not use it as the
programmer using the Robot class - Not accessible by programmer
- e.g. in simplerobot.cpp, programmer cannot modify
xPos
20How to
- How to define objects?
- class_name object_name_list_separated_by_comm
a - 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.
21How 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 robots
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 are called reference
parameters
Recommended since you generally change the robot
characteristics in functions
22Some 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 (xgt0) Robot r(x, 0) r.Move(3) r.Move
()
Undeclared identifier
23Compiling, Linking
- Single file case
- 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 (included) - library function bodies are ready in object code
- linked
myprog.cpp (source code)
myprog.obj (object code)
myprog.exe
compile
link
24Compiling, 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
simplerobot.cpp
int main () Robot Ali(5, 1) Ali.SetColor(white
) Ali.Move(5) return 0
simplerobot.obj
robots.cpp
robots.obj
RobotRobot (int x, int y, xPos x yPos
y direction dir color yellow ...
libraries
1101010101101010100110010101010 ...
25include
- Kind of copy-paste
- specified header file is copied before
compilation - 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 - difference between (this is very important)
- include ltfilenamegt
- 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
26Adding 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 to the project for these
libraries - 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!