Chapter 1: Introduction To Object Oriented Programming
Chapter 1: Introduction To Object Oriented Programming
Chapter Objectives
Upon completion of this module, you will have: learnt the concept of structured programming; discussed the drawbacks of structured programming; understood the concept object oriented programming; discussed the drawbacks of object oriented programming; understood an object oriented design concept.
1-1
CS255
1.1
Structured Programming
Features of Structured Programming : This programming technique was introduced and commonly used during the 1970s and 1980s. A program is viewed as big procedure which is the forefront of the program. Every real world problem is first changed into a procedure that logically progresses to the desired result. The big program is then broken into smaller components and each is just a procedure that solves a portion of the big procedural problem. With this approach, all real world problems are first converted into computer problems. Every problem must be solved by step-by-step instructions. This is mainly because the computers of old could only perform one step in a set of instructions at a time. Another major feature is that data and procedures are separated.
Database
Shared data
Figure 1 - 1 The separation of data and procedure and creation of more structured systems helped systems grow without losing maintainability. Another advantage of using structured approach is modularity.
1.2
1-2
CS255
When large problems are solved using this approach, diagrams representing the data flow through various procedures are drawn. The procedures are broken into functional groups. Programmers are assigned to develop each of the functional groups. As different problem solving techniques change with different interpretations of the problem, these changes trickled down into the various functional groups. The changes may be widespread throughout the various parts of the program. After all, all the procedure groups are smaller functional units of the whole, they are all intertwined in solving the big problem. Hence, decoupling cannot be easily achieved. Software is hand-crafted for a particular task and reuse of libraries are difficult to build as the procedures and data structures they operate are separate. As an example of the structured approach consider your computer. Note how a character appears on the screen when you type a key. In a procedural environment you write down the several steps necessary to bring a character on the screen: wait, until a key is pressed. get key value write key value at current cursor position advance cursor position You do not distinguish entities with well-defined properties and well-known behavior.
1.3
Object-Oriented Programming
A program is a model of reality, like a globe is a model of the world. In developing applications, we take what we want from the real world and put it in our model. For example, some globes show climatic features, some show geographical features, etc. Programmers often describe their programs in terms of concepts that are more easily represented such as objects, that relate to our real world. In OOP, processes are associated with data structures that represent the concepts of our application. The application is described in terms of the interaction of its component objects. With the object oriented approach, the system is conceived as a dynamic network of 1 2 collaborating objects . Objects are instances of classes . Each object has data and procedures that process the data. To view a program as a collection of interacting objects is a fundamental principle in object-oriented programming. Objects in this collection react upon receiving of messages3, changing their state according to invocation of methods which might cause other messages sent to other objects.
Definition (Object) An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time. Definition (Class) A class is the implementation of an abstract data type (ADT). It defines attributes and methods which implement the data structure and operations of the ADT, respectively. Definition (Message) A message is a request to an object to invoke one of its methods. A message therefore contains the name of the method and the arguments of the method.
1-3
CS255
Object 2 datum 3
Method C Method D
Figure 1 - 2 In figure 1-2, the program consists of only four objects. These objects send messages to each other, as indicated by the arrowed lines. With such a mechanism, individual objects or frameworks of objects could be reused more effectively. Above all, other important relationships such as association, assembly and inheritance4 can then be applied between objects. For the same example in key entry, in an object-oriented environment you would distinguish the interacting objects key and screen. Once a key receives a message that it should change its state to be pressed, its corresponding object sends a message to the screen object. This message requests the screen object to display the associated key value.
1.4
Inheritance : Ability to derive types based on previously defined types. Operations on the parent type apply to the derived type. Encapsulation : Grouping of essential characteristics
1-4
CS255
A class of sphere can be a base class of a ball class. A ball is a sphere. Yet a ball-pen class can be derived from a ball class. A ball-pen has a ball, of course a small one at the tip. Properties of sphere class could be applied to ball class, for instance, both have a diameter. OOP also allows polymorphism6 and dynamic binding7. A collection of objects that are derived from the same base class may have different operations in common , but the way each object performs the operation may be different depending on the type of the object. The division operator (/) is a example of polymorphism. The result of the division would be different if the data type of the operands are different. For instance, for integral operands, the answer is an integer : 3 / 2 = 1 however, if the operands are of float type, the answer is a float : 3.0/2.0 = 1.500000. Notice that the operator (/) is the same. Yet, the answer differs! This is an example of 8 polymorphism and this special type is known as operator overloading .
1.5
players,
radio
tuner,
CD,
cassette
tapes,
radio
Polymorphism : The ability to use the same procedure name or operator with different arguments. The term has an implication that the different type form a hierarchy. Dynamic Binding : Association of a specific item at run time. Needed if resolution is not resolvable at compile time. Overloading : Ability to use the same procedure name or operator with different types of arguments.
1-5
CS255
A player is a base type of CD player and tape player - an abstract class. Media being played, tapes and CDs are another abstract class. Another implied abstract class is control, which could be digital or analog controls for frequency tuning and bass level control. Adjectives describe the data members within the objects. For example the domestic model must have FM and AM radio frequency capability while the international model includes short wave SW band capability.
1-6
CS255
1-7
2-1
CS255
2.1
2.2
Common programming problems: Same identifiers are used with different letter format. C++ is case sensitive. It distinguishes between uppercase and lowercase characters. Identifiers are predefined keywords in C++. Programmers should be careful in defining identifiers. They should, as far as possible, be meaningful.
2-2
CS255
Blocks C++ is a block structured language. Blocks are defined as: { }. Blocks are generally used when there is more than one instruction to be executed at a point of condition checking. Declarations It is a characteristic of many computer languages that variables must be declared before they can be used. A variable declaration gives a name to the variable, and tells the computer what type of data this variable can hold. C++ syntax: Type Name; Example: int char float counter; // defines a variable called counter of type int transaction-type; price;
The type of a variable will determine the operations that can be performed upon it. There are operations that are sensitive to the type declared. For example / which is the division operator would produce different results if the operands are integers or if they are float. So be careful with the choice of type. Sometimes, logical errors could be caused by these and are easily overlooked. Assignment One way to change the value of a variable is by assignment. Almost all computer languages support this operation but each will use a different symbol. The assignment operator in C++ is =. Everything to the left of = is called a L-value. This will normally be a variable name. Everything to the right of = is called a R-value. This will normally be an expression. Normally both the variable and expression will be of the same type. Example: Area = pi *radius*radius; Basic C++ int char float Data Types whole numbers for example : 1,5,103, 8945 character (usually in ASCII) : `A`, `B`, `f`, `m`. Each character must be defined in single quotation marks. floating point number or number with decimal or fractional components. For example, 1.23, 3.14 bigger floating point number that is able to store more accuracy or larger numbers.
double
Example: int i; float x, y; char c; Type Modifiers Type modifiers are basically used to extend the basic data types. These are generally used to change the amount of storage used for any given type. These modifiers are : short, long signed, unsigned may allow a larger or smaller internal representation. controls whether or not a sign bit is kept, to declare a pointer.
2-3
CS255
Example: unsigned long int x; char * p; The table below shows the basic type and the data types organised by size, from smallest to largest. Category Character Signed integer Unsigned integer Floating point Data types Char Short unsigned short Float organised by size, signed char int unsigned double from smallest signed char long unsigned long long double
Literal Constants Several characters have names that used a backlash notation which is useful when you want to embed one of these characters within a literal characters string. Some examples Constants Name \n New Line \t Tab \ Single quotation mark \ Double quotation mark \0 Zero Expressions An expression is something that can be evaluated. The simplest form is an arithmetic expression. Arithmetic only work on numerical variables. C++ operators are: + addition subtraction * multiplication / division % modulus (reminder) Precedence The compiler resolves ambiguity by assigning a precedence to each operator. In C++, this precedence is (from high to low): ( ) * / + Input/Output in C++ I/0 is accomplished by the use of an I/0 operator, output operator << and input operator >>. Scope A variable defined within a block has a scope extending from the point of declaration to the end of the block. #include ... ... numeric variablel; string name; ....
2-4
CS255
These variables declared above are global, their definition is valid from here to the rest of the source file. SomeFunction( ) { .... variablel = 0; ... The global variables are accessible in any function. }
Variable Destruction
When your program runs, variables are literally destroyed when control leaves their scope. This explains why scope works. Variables are only created when the block they are defined in is executed. As soon as the end of the block is reached the variable is destroyed. Example of Scope Errors: Example 1 This program does not compile. #include <iostream.h> main( ) { int one; {int two;} one = two; }
Example 2. This program compiles, but does not run correctly. #include <iostream.h> int one; main( ) { do { int one ; cout << "Enter number:; cin >> one; }while (one != 0); cout << one << endl; } What is the problem?
2-5
CS255
Example 3 This program compiles, but does not run correctly. #include <iostream.h> main( ) { int two = 0; do { int one = 0; cout << one << endl; one = one + 1; two = two + 1; }while (two < 5); } What is the problem ?
Control Structures
The if Statement looks like this: if (logical expression) { // code to be executed if logical expression is true } else // this part is optional { // code to be executed if logical expression is false } Logical Expressions Logical expressions evaluate to true or false. Just as in C, there is no boolean type in C++. A result of true in an expression is denoted by a 1 and false is denoted by a 0. A simple logical expression is composed of two variables and a relational operator. Logical expressions can be formed by more than one simple logical expressions and are joined using logical operators. Relational Operators C++ has the following relational operators: == equal !=, <>, # not equal < less than > greater than <= less than or equal to >= greater than or equal to
Common programming error if (x == y) ... is perfectly legal in C++ but it does not do what you think it does! It assigns x to y but x is not check against y for equality. C++ Logical Operators && and | | or ! not
2-6
CS255
Bitwise operators & bitwise AND operator | bitwise OR operator ~ bitwise NOT operator ^ bitwise XOR operator Iterative or looping constructs 1. while statement while (logical expression) // a while loop { // body of loop } do // a repeat loop { // body of loop }while (logical expression) Example: while loop int age; cout << "Enter age; cin >> age; while (!((age >= 0 ) && (age <= 120))) { cout << "Enter age; cin >> age; } Example: repeat loop int age; do { cout << "Enter age; cin >> age; }while (!((age >= 0) && (age <= 120)));
2.
The for statement A loop construct especially useful with arrays is the for loop. Its syntax looks like this: for (initialisation; continuation condition; loop code) { //body of loop } Initialisation: statement executed once before the loop starts. Continuation condition: must evaluate true or false, loop will continue while this is true. Loop code: statement executed every iteration of the loop, after the body.
2-7
CS255
Example: for loop // print out the first 10 odd numbers for (int i = 1; i < 20; i +=2) { cout << i << end; }
3.
The switch statement switch is the C++ version of a case statement. switch ( ) { case : break; case : break; default : }
Example: switch cout << "Enter a number between 1 and 5; cin >> num; switch (num) { case 1 : cout << "you entered 1 " << endl; break; case 2 : case 3: case 4: case 5: cout << "you entered 2, 3, 4, or 5" << endl; break; default : cout << "your number was out of range"; } Functions Modules are defined in C++ as functions. In that returns a value. That value then replaces program. Functions must be declared before function B, the declaration of function A must definition of function B.
general, a function is a piece of code the function call at that place in the they are used. If function A uses precede (in source code sequence) the
Function Declaration returnType functionName (parameterList); returnType states the type of data returned. functionName is the meaningful representation of the module functionality. parameterList, is a list of input and output parameters expected. Parameter List The parameter list in function declaration defines the data to be passed to the function. This should be the only data accessible by the function. Format: returnType functionName (parameterType parameterName,....); parameterType defines the type of the data. parameterName is the name by which this data is known within this function, and may be (in fact, usually is) different to its name in the calling module.
2-8
CS255
Parameter Rules The function call must specify the same number of parameters as the function declaration and definition. The parameters must be specified in the same order, and must be of the same type. Value and Reference Parameters There are two ways a parameter may be passed to a function. 1. Value: If a parameter is passed by value, the function received a copy of the data. It cannot change the data in this parameter. Reference: A pass by reference parameter may be changed by the function.
2.
Example 1: Incorrect version of swap // interchange the values of two numbers void swap (int one, int two) // parameters are passed by value. { int temp; temp = one; one = two; two = temp; } Example 2 : Correct version of swap // interchange the values of two numbers void swap (int &one, int &two) // parameters are passed by reference. { int temp; temp = one; one = two; two = temp; } Sample Program 1: #include <iostream.h> void display (int); main( ) { int x = 1; display (x); for (int i = 0; i < 3; i++) { int y = x + i; display (y); } } void display (int num) { cout << "Value in display } Output:
2-9
CS255
Function Prototypes A prototype consists of the return type, the identifier of the function, and the types of all the parameters that the function expects. This permits type checking at compile and link time. In C++, every function must be defined or declared (prototyped) before it is used. stdlib.h prototypes all the calls in the standard C library. Also, the C++ version of standard I/0, iostream.h, header file declares all the stdio library calls. Data Declarations Not at the Top of Blocks In C++, it is not necessary to declare all data variables at the top of their blocks. Declarations may be made anywhere before they are first used. The scope of such variables is after their declaration, within the block of their declaration. Declarations of Parameters in the Parentheses Parameters of all functions are declared within the parentheses of the function definition, not on the lines between the function identifier and the opening curly brace. Simply place the data type of each parameter before its identifier in the parameter list. The void Data Type in the Function Interface The void data type as a return type indicates that the function does not return a value. This allows the compiler to catch return statements in the void function that return a value or attempt to assign a value from a void function. The void data type as a parameter list indicates that the function does not take any parameters. Empty parentheses are equivalent to specifying void as the parameter. End-of-line Comments // Everything on the program line to the right of the // characters is ignored and removed by the preprocessors. One benefits of these comments is the ability to place them within a block style comment. Since block style comments cannot be nested, these comments offer the ability to nest comments within comments. The cout Object and endl cout is the C++ alternative to the printf( ) library call. It is an object declared in the iostream library and requires the iostream.h header file. The << operator (called the insertion operator) follows the cout object. The item to be displayed follows the << operator. If other items are to be displayed, use another << operator followed by the next item to be displayed. This continues until all items are listed. endl is a manipulator for cout. The endl manipulator prints a newline character and then flushes the standard output buffer. Tagnames as Data Types In C++, tagnames can become data types, after the declaration of the data types. Use of the cin Object cin is used to read from standard input (stdin). The >> operator (extraction operator) is used. The right hand operand of the >> operator determines the type of data to be read from the stdin. Reading stops when the input no longer matches the type being sought, White space is not read. If the data type in the input stream does not match the data type requested, the input stream is marked with an error flag and data is
not transferred.