You are on page 1of 18

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

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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.

program A ..... ....................... . program B ..... ....................... . program C ..... ....................... .

Database

program D ..... ....................... .

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

Drawbacks of Structured Programming


Refinements and breaking of problems into parts may result in spaghetti code. It becomes increasingly difficult in controlling which procedures have access to which data. Changing one variable may have adverse effects on the whole program. In an attempt to solve the problem, structured design emphasize the importance of decoupling the parts as much as possible, limiting the number of procedures that access data to a controlled few.

1-2

CS255

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

CS255

Object 1 datum 1 datum 2 Method A Method B

Object 2 datum 3

Method C Method D

Object 3 datum 4 datum 5 datum 6 Method E

Object 5 datum 7 datum 8 Method F Method G

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

Benefits of Object Oriented Programming (OOP)


The core element of OOP is the encapsulation of an appropriate set of data types and their operations. The class construct and its functions and data members, provide an appropriate coding tool. Encapsulation is a process of combining smaller objects into a larger element that can be treated as a whole. Such encapsulation is seen in Pascal as the record structure and in C as the struct. Classes also provide data abstraction and data hiding. An abstract data type is a user defined type that consists of public interface which specifies how the object can be used (also acts as a message passing mechanism and a private implementation that is used to implement the behaviour specified by the public interface). Access privileges are managed and limited to whatever group of functions that need access to implementation details. This promotes modularity and robustness. For example, an Employee class could be built to contain all employee information and processes. Jim is an object of the Employee class, in other words, an instance of the class. It is identified that a function set_salary() is required for this employee class. Another important concept of OOP is the promotion of code reuse through the inheritance mechanism. This is the mechanism of deriving a new class from a base class. The derived class could be derived by altering or adding new properties to the base class.
5

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

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

Object Oriented Design Concepts


There are many thoughts on the steps in the OOD process. The following steps are in accordance of the Booch model being the first formalized model. The steps can be performed in series. 1. 2. 3. 4. 5. 6. Identify the problem and identify the real world objects. Identify the methods or activities that define the objects. Identify and establish object visibility. Establish the interfaces. Establish the object classes. Implement or reiterate the design

Identify the problem and identify the real world objects


This phase is like the planning phase of the system design methods. This focuses on the design goals as well as identifying the objects involved in the problem. The problem is first put into words and written down. Objects in a problem are represented as a noun in the written description. For example, to design a stereo system emulator, the problem is described as follows : A stereo system can be a CD system, a tape player and a radio. It is used to play music CDs, to play cassette tapes, and to tune in to radio stations. All of these controlled through mechanical control knobs on the system. Nouns are : stereo system, stations/frequency and controls.
6

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

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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.

Identify the methods or activities that define the objects


What the objects can do, or what are the operations that make the objects what they are? Methods are often identified by verbs. Some verbs in the descriptions are play, tune and adjust. Tuning is for adjusting so only one of it is required. These methods are associated to the respective objects.

Identify and establish object visibility


In this step, the things in the object that other objects must know is identified. For example, must the tape played need to know that the radio is playing?

Establish the interfaces


The next step is to determine how all parts interact to make the system. The interface is the group of activities that ties the objects to the outside world. In the stereo system example, the control class is the interface. The control class gets user commands to adjust the volume and sends messages to the stereo components to perform those choices. A speaker class may be added and has the control class to adjust the volume of the speaker class. Listeners need some feedback on their adjustment. Such feedback could be in the form of a lighted level indicator.

Establish the object classes


The methods of the classes could be represented as pseudocode and the header files could be created. A consideration should be given as to whether volume should be integer or float?

Implement or reiterate the design


The act of solving problem often defines how it is to be solved. An object that is incorrectly designed could be added on and made right. Methods that are not usable should not be discarded as their presence may be needed one day. In most cases, reuse of classes usually requires changing of other projects. When maintenance is performed, care must be taken to ensure that classes can still be reused in other projects. A newly derived class specific to the current program may be created, keeping the current class. In any event, you see how each step in the design uncovers more thoughts on the earlier step and helps in the fine tuning the concepts are one proceed. This is a strength of OOD. Each step clarifies, without complicating, the design.

1-6

CS255

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

1-7

CHAPTER 2 : INTRODUCTION TO C++


Chapter Objectives
Upon completion of this module, you will learn about: the history and evolution of C++; some text resources available; the basic features of the C++ language; the use of some basic C++ features.

2-1

CHAPTER 2 : INTRODUCTION TO C++

CS255

2.1

History and Introduction of C++


C++ was developed by Bjarne Stroustrup at AT&T in early 1980s. C++ is based on C and it retains much of that language, including a rich operator set. C++ is a highly portable language, and translators for it exist on many different machines and systems. C++ compilers are highly compatible with the existing C programs because maintaining such compatibility was the design objective. Programming in C++ does not require a graphics environment, and C++ programs do not incur runtime expense from type checking or garbage collection. C++ has improved on C in significant ways, especially in supporting strong typing. The class syntax was added to the language which was an extension of the struct construct in C. C++ is superior than C in supporting object-oriented programming. C++ may even replace C in becoming a general purpose programming language.

2.2

Some C++ Basics


A First C++ Program #include <iostream.h> // this outputs 'hello world' to the terminal main( ) { cout << "hello world" << endl; } White Space You will frequently see references to something called white space. It is typically used to separate different words in a program. White space consists of one or more of space, tab and newline The Judicious use of white space can make your programs much more readable. Comments // and /*....*/ comments in C could be used for representing remarks. Identifier and keywords Just as many programming languages, C++ identifier is a sequence of letters, digits and underscores that must begin with a letter or an underscore.

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

CHAPTER 2 : INTRODUCTION TO C++

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

CHAPTER 2 : INTRODUCTION TO C++

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

CHAPTER 2 : INTRODUCTION TO C++

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

// variable one is a global variable // variable two is a local variable

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

CHAPTER 2 : INTRODUCTION TO C++

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

CHAPTER 2 : INTRODUCTION TO C++

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

CHAPTER 2 : INTRODUCTION TO C++

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

CHAPTER 2 : INTRODUCTION TO C++

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:

" << num << endl;

2-9

CHAPTER 2 : INTRODUCTION TO C++

CS255

Value Value Value Value

in display = 1 in display = 1 in display = 2 in display = 3

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.

You might also like