Object-oriented Programming (COM 357J) Lecture Week -1 Dr. Nazmul Siddique, Room MS137, ext 75340, email: nh.siddique@ulster.ac.uk, URL: http://www.scis.ulster.ac.uk/~siddique Weeks 1-8 will cover Week Topics 1 OOP Overview and introduction to C++ 2 Decision making in C++ 3 Looping structures in C++ 4 Functions in C++ 5 Arrays and pointers in C++. 6 Classes and objects in C++ 7 Constructors and destructors in C++ 8 Inheritance and inheritance hierarchies in C++ 9 Class Test in week 9 - 1 hour duration Pointers to objects, virtual & abstract class 10 Virtual functions and Polymorphism 11 Class template, function templates, STL in C++, File handing in C++ 12 Feedback and tips on final exam Assessment Specification (Issued in lecture of week 1) Course work 50% CW1 – A one-hour class test worth 50% of CA covering all topics from week 1 to week 8 will be held in week 9. Date of the class test is flexible. Please inform lecturer if you have a placement interview on the date. There will be 6-8 questions. You have to answer all questions. CW2 – An assignment/open book lab test based on lab exercises from week 1 to week 9 worth 50% to be submitted/will be held in week 10. In each week you will be given small problems to work out within the lab hours. You have to demonstrate to the lecturer/demonstrator on completion of the tasks. Lecturer/demonstrator will keep a record of it. You will keep your portfolio of all your programs in a folder on your U drive. You will need these worked out exercises for the assignment/open book lab assessment. Written Examination (Final exam): 50% Duration 3 hours There will be two sections in the exam paper: Section A: Compulsory part consists of six questions and worth 60%. Each question is worth 10 marks. You have to answer all six questions from Section A. Section B: Optional part consists of 4 questions and worth 40%. You have to answer 2 questions from Section B. Past exam papers can be found on Library website. A past exam paper with solution is also on module website. Procedure-oriented Programming In procedure-oriented approach, the problem is seen as a sequence of things to be done, such as reading, calculating and displaying. A number of functions are coded to accomplish these tasks. A typical program is shown in Figure 1. Main Program Function-1 Function-2 Function-3 Function-4 Function-5 Figure 1: Typical structure of procedure-oriented programming. Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow, and organising these functions into groups known as functions. We concentrate mainly on the development of functions; very little attention is given to the data that are being used by the functions. In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function has its own local data. Figure 2 shows the relationship between data and functions in a procedure-oriented program. Global Data Global Data Function-1 Function-1 Function-1 Local data Local data Local data Figure 2: Relationship of data and functions in procedural approach. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we have to revise an external data structure, we should also revise all functions that access the data. This provides an opportunity for bugs to creep in. Another serious drawback with the procedure-oriented programming is that it does not model real world problem very well. This is because functions are action-oriented and do not really correspond to the elements of the problem. Object-oriented Programming Object-oriented-programming (OOP) is an approach to program organisation and development Object-oriented programming (OOP) treats data as a critical element in the program development and does not allow it to flow freely in the system. It ties data more closely to the functions that operate on it and protects it from accidental modification from outside functions. OOP allows us to decompose a problem into a number of entities called objects and then builds data and functions around these entities. Organisation of data and functions on OOP is shown in Figure 3. In OOP, functions are called methods. Object Data Function Object Data Function Methods Function Function Figure 3: Object-oriented approach. The data of an object can be accessed only by the function associated with that object. Functions of one object can access the functions of the other object. Figure 4 shows part of a solution based on an object-oriented architecture. StudentInfo: Object Data Method1 Method 2 CourseReport: Object Data Method 3 Method 4 Figure 4: Object-oriented architecture. For example: StudentInfo object might have a string name, an array of double marks[10]. CourseReport object might be a bit like a spreadsheet and have names and summary marks for each student. The program proceeds by objects communicating between one-another via their methods. Data are sent via methods; data are requested and returned via methods. This execution of an object-oriented program is shown in Figure 5. StudentInfo: Object Data Method1 Method 2 CourseReport: Object Compute overall marks Overall marks Data Method 3 Method 4 Figure 5: Program executes via message passing. Basic Concepts of Object Oriented Programming Object-oriented programming is an approach to organizing programs i.e. it is not applicable to all programs. OOP becomes increasingly helpful as programs grow larger. Let us discuss object-oriented programming using the following concepts: (i) Objects (ii) Classes (iii) Data abstraction (iv) Data encapsulation (v) Inheritance (vi) Polymorphism (vii) Dynamic binding (viii) Message passing Basic C/C++ Programming Variables, Constant, Operators, Expressions and Data types Variable Names Every variable has a name and a value. Name identifies the variable and the value stores data. Every variable name in C/C++ must start with a letter and the rest of the name can consist of letters, numbers and underscore characters. C/C++ recognises upper and lower case characters as being different. Any of C/C++'s keywords like main, while, switch etc cannot be used as variable names. Examples x x1 impetus result x_2 gamma outfile out_file hi_score bestyet best_yet It is conventional to avoid the use of capital letters in variable names. These are used for names of constants. Most modern ones don't apply this limit though. Rules governing variable names also apply to the names of functions. Variables A variable must be declared before it can be used. Variables can be declared at the start of any block of code Most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function. Declaration begins with the type, followed by the name of one or more variables. The syntax is as follows: type variable_list; Example int high, low, results[20]; Variables can also be initialised when they are declared by adding an equal sign and the required value after the declaration. Example int high = 250; /* Maximum Temperature */ int low = -40; /* Minimum Temperature */ int results[20]; /* Series of temperature readings */ C/C++ provides a wide range of data types, see section on Data Types. Basic data types can have modifiers to meet the demand of precision in programs. Basic form of modifiers is signed, unsigned, long and short. Use of modifiers are as follows long double Example short int high = 250; /* Maximum Temperature */ long double results[20]; /*temperature readings */ Local and Global Variables Local variables are declared within the body of a function, and can only be used within that function. Alternatively, a variable can be declared globally so it is available to all functions. They can lead to poor program structure, and tend to clog up the available name space. A global variable declaration looks normal, but is located outside any of the program's functions. External Variables Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable Declaration must be preceded by the word extern. Declaration is required so the compiler can find the type of the variable without having searched through several source files for the declaration. Static Variables Static variable is not destroyed on exit from the function, instead its value is preserved, and becomes available again when the function is called next. Static variables are declared as local variables, but the declaration is preceded by the word static. Example static int counter; Static variables can be initialised as normal, Initialisation is performed once only when the program starts up. Constants A constant in C/C++ is usually the written version of a number. For example: 1, 0, 5.73, 12.5e9. A constant can be specified in octal or hexadecimal, or force them to be treated as long integers. Character constants are usually the character enclosed in single quotes e.g. 'a', 'b', 'c'. A string constant is surrounded by double quotes e.g. "Ryan and Doherty". String is actually stored as an array of characters. Null character '\0' is automatically placed at the end of such a string to act as a string terminator. A character is a different type to a single character string. Assignment Statement The easiest example of an expression is in the assignment statement. An expression is evaluated, and the result is saved in a variable. Example y = (m * x) + c; This assignment will save the value of the expression in variable y. These can cause confusion if you try to do too many things on one command line. Operators and Expressions One reason for the power of C/C++ is its wide range of useful operators. An operator is a function, which is applied to values or variables for mathematical or logical manipulations e.g. +, && and >> denote arithmetic addition, logical AND and right shift operations respectively. There are three general classes of operators used in C/C++: Arithmetic operators, Relational and Logical and bitwise. Arithmetic operators are the most common. Other operators are used for comparison of values, combination of logical states, and manipulation of individual binary digits. The binary operators are rather for low-level operations and are not covered here. Table 1: Arithmetic operators Operators Action Subtraction + Addition * Multiplication / Division % Integer division -Decrement ++ Increment Table 2: Logical operators Operators Action && AND || OR ! NOT Table 3: Relational operators Operators Action > Greater than >= Greater than or equal < Less than <= Less than or equal == Equal != Not equal Expressions Operators, variables and values are combined to form expressions. Values produced by the expressions can be stored in variables, or used as a part of even larger expressions. Example int count; float time,mass; double distance, force, initial_velocity, acceleration; force = mass * acceleration; count = count + 1; distance=initial_velocity*time+0.5*acceleration*(time*time); velocity = distance / time; Operators such as *, / and % will be performed before + or - in any expression. Brackets can be used to force a different order of evaluation to this. If a program is ever required to divide a number by zero, this will cause an error, usually causing the program to crash. Example: y=x + a*b – (25.98+a); //Expresion consists of 3 variables and a value C/C++ has some operators, which allow abbreviation of certain types of arithmetic assignment statements. They can be combined with another expression. Example f = m * a; count++; //count=count+1 ++count; //same as count++ count--; //count=count-1; --count; //same as count--; d=v*t+0.5*a*(t*t); v += d; //v=v+d v *= d; //v=v*d; Comparison or Relational operation C/C++ has no special type to represent logical or Boolean values. It improvises by using any of the integral types char, int, short, long, unsigned, with a value of 0 representing false and any other value representing true. It is rare for logical values to be stored in variables. They are usually generated as required by comparing two numeric values. This is where the comparison operators are used. They compare two numeric values and produce a logical result. Note that = = is used in comparisons and = is used in assignments. Comparison operators are used in expressions like the ones below. x = = y; i > 10; (a + b) != c //(a+b) NOT = c; In the last example, all arithmetic is done before any comparison is made. These comparisons are most frequently used to control an if statement or a for or a while loop. Logical Connectors These are the usual And, Or and Not operators. They are frequently used to combine relational operators, for example x < 20 && x >= 10 They evaluate their left hand operand, and then only evaluate the right hand one if this is required. Clearly false && anything is always false, true || anything is always true. In such cases the second test is not evaluated. Not operates on a single logical value, its effect is to reverse its state. Example if ( ! acceptable ) printf("Not Acceptable !!\n"); if(x < 20 && x >= 10) printf("Valid number !!\n"); Type casting You can mix the types of values in your arithmetic expressions. Variable is too small to hold the value. In this case it will be corrupted (this is bad). Variable is an integer type and is being assigned a real value. Function has no way of determining the type passed to it, so automatic conversion cannot take place. Solution is to use a method called casting which temporarily disguises a value as a different type. Example: Function sqrt finds the square root of a double. int i = 256; int root; root = sqrt( (double) i); Cast is made by putting the bracketed name of the required type before the value (double) in this example. Result of sqrt( (double), i) is also a double, but this is automatically converted to an int on assignment to root. Input & output C/C++ library contains a rich and diverse assignment of I/O. Console I/O refers to operations that occur at keyboard and screen of the computer and can be classified into following: Simple console I/O function Formatted console I/O function Console I/O functions Simplest of all console I/O functions are: reading a character from standard input usually keyboard writing a character to standard output usually screen. getche(), getchar(), getch() Reads a character from keyboard. getche() function waits until a key is pressed and then return its value. Key pressed is also echoed to the screen automatically. getchar() takes input until a carriage return is entered. getch() similar to getche() except that the character pressed is not echoed to the screen. Syntax: Variable_name = getche(); Variable_name = getchar(); Variable_name = getch(); Example main() { char name1, name2, name3; name1=getche(); name2=getchar(); /* need to press enter key */ name3=getch(); } getchar(), getche() and getch() can also be used without variable assignment. Putchar() Print a character to the screen at the current cursor location. Syntax putchar (variable_name); Where variable_name is a character type variable. Example main() { char name; name = getche(); putchar(name); putchar(‘\n’); } gets(),puts() gets() and puts() enable reading and writing a string of character at console. gets() function reads a string of characters entered at the keyboard, until a carriage return is pressed. Carriage return does not become the part of the string; instead a null terminator is placed at the end. Syntax gets(variable_name); Where variable_name is a character string. Example main() { char name[10]; gets(name); } The puts() function writes a string followed by a new line. Syntax puts(string / variable-name); Where string is a sequence of characters enclosed with console quotation marks and variable_name is a string. Example main() { char name[10]; gets(name); puts(“Hello”); puts(name); } The simplest function that perform console I/O operations are summarized below Function getchar() getche() getch() putchar() gets() puts() Operator Reads a character form the keyboard and waits for carriage return. Reads a character with echo and does not wait for carriage return. Reads a character without echo and does not wait for a carriage return. Writes a character to the screen. Reads a string form keyboard and terminated with a carriage return. Write a string to the screen followed by a new line. Formatted console I/O In addition to simple console I/O functions, C/C++ provides two functions that perform formatted input and output on the built-in data types. scanf() scanf() is a formatted input function. Formatted refers to the fact this function can read data form keyboard in various format that is under user’s control. Syntax: scanf(“control string”,&var1, &var2,... ... ... &var n.); Control string specifies the field format and var1,var2... ... ... var n specifies the name of the variable preceded by the address operator & i.e. &var1,&var2 ... ... ... &var n specify the memory locations where data is to be stored. Control string consist of conversion character % and a data type character or type specifier, and/or write space characters such as space, a tab, a newline. Example scanf(“%d”,&number); /*reads a decimal integer */ scanf(“%c”,&name); /*reads a single character */ scanf(“%f”,&real); /*reads a real number */ Type specifiers for scanf() are given in Table1 below. Code %c %d %i %f %e %n %o %s %x %p %n Meaning Read a single character. Read a decimal integer. Read a decimal integer singed. Read a floating point number. Read a floating point number in exponential form. Read a short integer. Read an octal number. Read a string. Read a hexadecimal number. Read a pointer. Read an integer value equal to the number of character. Space, tabs or new line must separate input data items. Don’t use comma or other punctuation marks. Example scanf(“%d %d”,&a,&b); Function will read data such as 62 and 17 correctly and assign 62 to a and 17 to b. Field width can also be specified such as follows scanf(“%2d %2c %5s”,&a,&b,s); Where a and b are integer variables and will read 2 digit values. S is character variable and will read 5 characters. If the number to be read is of double type, then the specification should be %lf instead of simple %f. Example scanf(“%lf %2.3f”,&a,&b); Reads the number e.g. 4142857142857 for double and 12.173 for float. Character string can be input with width specified Example scanf(“%5s”,name); /* & is not required */ scanf(“%5c”,name); /* & is not required when an array is used */ where name is character string declared as char name[5]. When %wc is used for reading a string, it will wait until w-th character is typed in. %s specification terminates reading at encounter of a space. Example scanf(“%s”,name); if Johan Karin is typed, only Johan will be read. scanf() function provides specifiers which specifies characters Example scanf(“%[a-d]”,choice) ; %[a-d] specifies that only a,b,c,d are read otherwise terminates input. Example scanf(“%[a,p,q]”,&choice); scanf() function can read all characters except character after circumflex. Example scanf(“[^x]”,&choice); scanf(“[^\n]”,&choice); scanf(“[^\n]”,name); /* where name is a character string */ It is possible to input mixed data type in one scanf() function. Example scanf(“%d %f %[^\n]”,&a,&b,name); printf() Formatted output, printf(), function refers to the fact it can write data to screen in various format under user’s control. Syntax printf(“control string”,var1,var2 ... var n); Control string consist of conversion character % and a data type character or type specifier, and/or white space characters such as \n, \t and \b. var1 ... var n are variables whose values are to be pointed. Example printf(“%d”,number); printf(“%d”,real_number); printf(“%d”,ch); Control string can be any string or empty string. Example printf(“Hellow Mr. x”); printf(“ ”); printf(“\n”); Type specifiers for printf() are given in Table2 below. Code %c %d %e %f %g %i %o %s %u Meaning Print a single character. Print a decimal number (integer). Print a floating point number in exponential form. Print a floating point value without exponential. Print a floating point either e- or ftype. Print a singed decimal integer. Read an octal integer without leading zero. Print a string. Print an unsigned decimal integer. Width of the output field can be specified. For example, no is a variable of type integer and assigned a value of 9876. It can be printed in the following format. printf(“%6d”,no); 9 8 7 6 printf(“%d”,no); 9 8 7 6 printf(“%-6d”,no); 9 8 7 6 printf(“%06d”,no); 0 0 9 8 7 6 Normally, printing is right justified. It is possible to force printing to be left justified by using a minus sign directly after % sign. Inputs and Outputs in C++ One of the most programmer-friendly C++ I/O function is the header file iostream.h which avoids the formatting requirements of such functions like printf() and scanf(). Output Operator The general form of the statement that prints a string is as follows: cout << Expr_1 << Expr_2 << ………<< Expr_n; cout (read as C out ) represents standard output stream. << operator (put to) causes the expression/ string on its right to be passed to cout and will be displayed. Expr_i is a C++ valid expression. Operator examines the type of the variable and prints accordingly. << operator can be used more than once. Example cout << “Mars is ” << miles << ”from the sum \n” cout << “Derry is ”<<miles << “away from Belfast \n”; Here ‘miles’ is the identifier. Example cout << sqrt(a*a+b*b) <<”\n\n”; cout << “The hypotenuse = ” << sqrt(a*a+b*b) <<”\n\n”; If white space is to appear in the output, it must be specified explicitly. Example cout << alpha << “ “ << beta <<\n”; cout << “The sum of “ << A << “and” << B << “ is “ << A+B << ”\n” ; Input Operator The general form of the statement that inputs a string is as follows: cin >> variable_1 >> variable_2 >> …….. >> variable_n; cin (read as C in ) represents the standard input device. >> operator (get from) takes the input from the device on its left and places it in the variables on its right. Operator examines the type of the variable and inputs/receives accordingly. Example cin >> ”27”; cin >> name; cin >> age; >> operator can be chained together. Example cin >> alpha >> beta; If alpha and beta are float type, the user enters the values 1.2 and 2.8. Data Types Data types in C++ can be classified under various categories as shown in Figure 1. C++ Data types Built-in type integral type int char float type Derived type User-defined type array function pointer structure union class enumeration void float double C++ compilers support all built-in data types int, char, float and double. The modifiers signed, unsigned, long, and short may be applied to int and char types. Modifier long may also be used for double type.