Object oriented programming Course Objectives Object Oriented Paradigm C/C++ Programming Language On completion of the class, a student should be able: to prepare object-oriented design for small/medium scale problems to demonstrate the differences between traditional imperative design and object-oriented design to explain class structures as fundamental, modular building blocks to understand the role of inheritance, polymorphism, dynamic binding and generic structures in building reusable code to write small/medium scale C++ programs with simple graphical user interface to use classes written by other programmers when constructing their systems to understand and to use fundamental data structures: collections, sets, dictionaries, lists, stacks, queues, trees, graphs.
Bibliography 1. A.V. Aho, J.E. Hopcroft, J.D. Ullman, Data Structures and Algorithms, Addisson-Wessley Publ., Massachusetts, 1983. 2. R. Andonie, I. Garbacea, Algoritmi fundamentali. O perspectiva C++, Editura Libris, 3. Alexandrescu, Programarea moderna in C++. Programare generica si modele de proiectare aplicate, Editura Teora, 2002 4. M. Frentiu, B. Parv, Elaborarea programelor. Metode si tehnici moderne, Ed. Promedia, Cluj-Napoca, 1994. 5. E. Horowitz, S. Sahni, D. Mehta, Fundamentals of Data Structures in C++, Computer Science Press, Oxford, 1995. 6. K.A. Lambert, D.W. Nance, T.L. Naps, Introduction to Computer Science with C++, West Publishing Co., New-York, 1996. 7. L. Negrescu, Limbajul C++, Ed. Albastra,Cluj-Napoca 1996. 8. Dan Roman, Ingineria programarii obiectuale, Editura Albastra, Cluj_Napoca, 1996. 9. B. Stroustup, The C++ Programming Language, Addison Wesley, 1998. 10. Bruce Eckel, Thinking in C++, www.bruceeckel.com 11. Mats Henricson, Erik Nyquist, Industrial Strength C++, Prentice Hall PTR, 1995 Activities: Lecture: 2h/week Seminar: 1h/week Lab:2h/week Grade: Lab grade (30%) - (70% lab + 30% partial) Practical Exam (30%) Written exam (40%) Seminar activity 0 0.5p Minimum grade >= 5 at Practical, Written and Lab grade Contact: Mail: istvanc@cs.ubbcluj.ro Course Web address: www.cs.ubbcluj.ro/~istvanc/oop
Content Lecture 1 - C Programming language data types, variables, statements Lecture 2 - Procedural programming in C functions,modules Lecture 3 - Memory management Pointers and references Lecture 4 - C++ programming language classes, objects, templates Lecture 5 - Inheritance, polymorphism derived classes, abstract classes Lecture 6 - Input/output stream, exceptions Lecture 7 - Graphical user interface Qt Toolkit Lecture 8 - GUI user interaction signals and slots Lecture 9 - GUI components Lecture 10 - Model-view-controller Lecture 11 - Standard Template Library containers, iterators Lecture 12 - Design patterns Lecture 13 - Memory management smart pointers Lecture 14 - Recap
Lecture 1 Object-oriented programming Introduction - OOP C Programming language syntax data types, variables, statements functions
Programming evolution Machine code programs in binary code, executed directly by the processor Assembly languages still low level programming, replaced machine code functions with mnemonics and memory addresses with symbolic labels Procedural programming decompose programs into procedures/functions Modular Programming decompose programs into modules Object Oriented Programming decompose program into a set of objects objects interact with each other to form a system
Object Oriented Paradigm Provide flexible and powerful abstraction Allow programmers to think in terms of the structure of the problem rather than in terms of the structure of the computer. Decompose the problem into a set of objects Objects interact with each other to solve the problem create new type of objects to model elements from the problem space An object is an entity that: has a local state able perform some operation (behavior) It may be viewed as a combination of: data (attributes) procedural elements (methods) Object Oriented Programming is a method of implementation where: objects are fundamental building blocks each object is an instance of some type (class) classes are related to each others by inheritance Fundamental concepts and properties Concepts: object class method (message) Properties: encapsulation inheritance polymorphism
C/C++ Programming Language Why C/C++: widely used, both in industry and in education is a high level programming language hybrid language, implements all the concepts needed for object oriented programming (C++) many programming languages are based on C/C++ (Java, C#). Knowing C++ makes learning other programming languages easier Advantages: Conciseness: allow us to express common sequences of commands more concisely. Performance: program written in c++ usually run faster than programs written in other languages Maintainability: modifying code is easier when it entails just a few text edits,instead of rearranging hundreds of processor instructions. Portability: can be used to write programs for nearly any processor Productivity: The goal of C++ is improved productivity (over C).
Compiled Languages. The compilation Process A program goes from text files (or source files) to processor instructions as follows: Source file - text file, contain the program in a programming language - compiler, parse the source files and create object files Object File - intermediate files that represent an incomplete copy of the program - linker, combine multiple object files and create the program that can be executed Executable - operating system, load the executable file into the memory and execute the program Program in memory In C/C++, all these steps are performed ahead of time, before you start running a program. In some languages, they are done during the execution process, which takes time. This is one of the reasons C/C++ code runs far faster than code in many more recent languages. Python (Interpreted) vs C/C++ (compiled)
Integrated Development Environment for C/C++ Compiler MinGW - - Minimalist GNU for Windows, a native Windows port of the GNU Compiler Collection (GCC) MinSYS - is a collection of GNU utilities such as bash, make, gawk and grep Eclipse IDE Eclipse CDC provides a fully functional C and C++ Integrated Development Environment based on the Eclipse platform. C Project Hello World sample application
Lexical elements C/C++ is case sensitive (a <> A) Identifier: Sequence of letters and digits, start with a letter or _ (underline). Names of things that are not built into the language Ex. i, myfunction, rez, Keywords (reserved words): Identifier with a special purpose Words with special meaning to the compiler int, bool, for, Literals: Basic constant values whose value is specified directly in the source code Ex. Hello, 72, 4.6, c Operators: Mathematical or logical operations +,-, << Separators: Punctuation defining the structure of a program ; {, ( ) Whitespace: Spaces of various sorts; ignored by the compiler space, tab, new line Comments: ignored by the compiler // this is a single line comment /* This is a * multiline comment */
Data types A type is a domain of values and a set of operations defined on these values. Built in data types: Name Description Size Range char Character or small integer. 1byte signed: -128 to 127 unsigned: 0 to 255 int Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits) double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) short int (short) long int (long) Short Integer. 2bytes signed: -32768 to 32767 unsigned: 0 to 65535 Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 operations: +, -, *, /, % relations: <, >, <=, >=, ==,!= short/long can be used to change the domain of the type signed/unsigned can be used to change how the value is interpreted (the sign bit) operations can be performed only on compatible types. Ex. Can t take the remainder of an integer and a floating-point number
Built in Data types in C/C++ void test_integers() { // ASCII "char" char c = 'a'; // at least 1 byte, signed assert(c == 'a'); c++; assert(c == 'b' && c == 98); //'b' synonym for the int value 98 c = 255; // -128..127 in case of 1 byte assert(c == -1); // so, it's true // Small integer short s = 1; // at least 2 bytes, signed // Default integer int i = 2; // at least 2 bytes (typically 4), signed // Large integer long l = 3; // at least 4 bytes, signed assert(s + i == l); void test_floating_points() { float f = 1.0; // single precision, typically 4 bytes double d = 1.0; // double precision, typically 8 bytes assert(f == d); float f2 = 1/3.0; // division assert(f2!=0.333); float f3 = 1/3; //! perform integer division assert(f3==0);
Arrays If T is an arbitrary basic type: T[n] - is an array of length n with elements of type t indexes are from 0 to n-1 indexing operator: [ ] compare 2 arrays by comparing the elements multidimensional arrays: t[n][m] #include <stdio.h> int main() { int a[5]; // create an array with 5 elements a[0] = 1; //index start from 0 a[1] = 2; printf("a[0]=%d \n", a[0]); printf("a[1]=%d \n", a[1]); //!!! a[2] uninitialised printf("a[2]=%d \n", a[2]); int b[] = { 1, 2, 3, 5, 7 ; printf("b[0]=%d \n", b[0]); b[0] = 10; printf("b[0]=%d \n", b[0]); return 0;
C String Represented as char arrays, the last character is '\0' (mark the end of the string) Handled as any ordinary array C include a standard library for string manipulation (<string.h>) strlen - Return the number of chars in a C string strcpy - Copy the characters from the source string to the destination string. -Obs. the assignment operator will not copy the string (or any array) strcmp - Compare two strings and return zero:a==b, negative:a<b, positive:a>b. - Obs. using ==,<,> operators on C strings (or any array) compare memory addresses strcat - Append the characters from the source string to the end of destination string Obs. None of these string routines allocate memory or check that the passed in memory is the right size. #include <stdio.h> #include <string.h> int main() { char name[100]; strcpy(name, "Popescu"); printf("name:%s l=%d", name, strlen(name)); char name2[100]; strcpy(name2, name); printf("name:%s l=%d", name2, strlen(name2)); while (getchar()!= 'e'){; return 0;
Record - composite type is a collection of items of different types. group various built-in data types into a structure. struct name{ type1 field1; type2 field2 //introduce a new type //called: struct car struct car{ int year; int nrkm; car c; c.year = 2010 c.nrkm = 30000; typedef - Introduce a shorthand name for a type #include <stdio.h> //introduce a new type called Car typedef struct { int year; int km; Car; int main() { Car car, car2; //initialise fields car.year = 2001; car.km = 20000; printf("car 1 fabricated:%d Km:%d \n", car.year, car.km); //!!! car2 fields are uninitialised printf("car 1 fabricated:%d Km:%d \n", car2.year, car2.km); return 0;
Variable declaration Introduce a name into the program and associate a type to the name. Memory is allocated according to the type of the variable. Variable is a named location in memory The type tell the compiler how much memory to reserve for it and what kinds of operations may be performed on it The value is undefined until the variable is initialized Can combine (recommended) the declaration with the initialization Use meaningful names for the variables Always initialize the variables with a meaningful value <type> <identifier> Ex. int i long rez int j=7 Constants numeric constants: 1, 12, 23.5 string constants: Hello World character: c
Rules and recommendations (Industrial Strength C++ Mats Henricson, Erik Nyquist) Names (variables, constants, types, functions...) If names are not chosen, written and administrated with care, then you will end up with a program that is hard to understand, read and maintain. Use meaningful names. Use English names for identifiers. Be consistent when naming functions, types, variables and constants Comments Specify every method using comments Inside a function/method: Comments are unfortunately hard to maintain, so with a few exceptions they should only explain what is not obvious from reading the program itself. Each file should contain a copyright comment. Each file should contain a comment with a short description of the file content. Each method should have specifications included in a comment Every file should declare a local constant string that identifies the file. Use // for comments. All comments should be written in English.
Pointing to data - Pointers - Pointers are designed for storing memory address - Can store the address of another variable, address of a memory location Declaration - same as declaring a normal variable except '*' in front of the variables identifier. Ex: int *a; long *a, char *a Operators - address of operator '&': - take the address of a variable - dereferencing operator '*' - get the value at the memory address pointed to #include <stdio.h> int main() { int a = 7; int *pa; printf("value of a:%d address of a:%p \n", a, &a); //assign the address of a to pa pa = &a; printf("value of pa:%d address of pa:%p \n", *pa, pa); //a and pa refers to the same memory location a = 10; printf("value of pa:%d address of pa:%p \n", *pa, pa); return 0;
Statements A statement is a unit of code that does something a basic building block of a program. An expression is a statement that has a value. Every statement is ended by: ; (except the compound statement) Empty statement: ; Compound statement: { //multiple statements here Assignment Assignment operator: = Assign a value to a variable (initialize or change the value of a variable)
Conditional: if, if-else and else if if (condition){ //statements executed only if the condition is true The condition is some expression whose value is being tested. If the condition resolves to a value of true, then the statements are executed before the program continues. Otherwise, the statements are ignored. If there is only one statement, the curly braces may be omitted. if (condition){ //statements executed if the condition is true else { //statements executed only if the condition is not true if (condition1){ //statements executed if the condition1 is true else if (condition2){ //statements executed only if condition1 is not true and the condition2 is true condition, condition1, condition2 - are expressions any expression has a numeric value a value equal with 0 is false, any other value is true
Conditional: switch-case switch(expression) { case constant1: statementa1 statementa2... break; case constant2: statementb1 statementb2... break;... default: statementz1 statementz2... The switch evaluates expression and, if expression is equal to constant1, then the statements beneath case constant 1: are executed until a break is encountered. If expression is not equal to constant1, then it is compared to constant2. If these are equal, then the statements beneath case constant 2: are executed until a break is encountered. If not, then the same process repeats for each of the constants, in turn. If none of the constants match, then the statements beneath default: are executed
Loops Loops execute certain statements while certain conditions are met. while and do-while while(condition) { statement1 statement2 As long as condition holds, the block of statements will be repeatedly executed. If there is only one statement, the curly braces may be omitted do { statement1 statement2 while(condition); The block of statements is executed and then, if the condition holds, the program returns to the top of the block. Curly braces are always required.
for loop for(initialization; condition; incrementation) { //body initialization - initialise one or more variables incrementation - executed after each iteration The for loop is designed to allow a counter variable that is initialized at the beginning of the loop and incremented (or decremented) on each iteration of the loop. As long as condition holds, the block of statements will be repeatedly executed. A for loop can be expressed as a while loop and vice-versa. for(initialization; condition; incrementation) { statement1 statement2 initialization while(condition) { statement1 statement2 incrementation
Instructions - loops #include <stdio.h> int main(int argc, char **argv) { //read 5 numbers int i=0; for (i=0;i<5;i++){ int nr = 0; printf("give a number[%d]:",i); scanf("%d",&nr); printf("number=%d\n",nr); //read numbers until user enters 0 int nr = 0; do{ printf("give a number (or 0 for exit):"); scanf("%d",&nr); printf("number=%d\n",nr); while(nr!=0); //divide number to 2 int number = 0; printf("give a number:"); scanf("%d",&number); int count = 0; while (number%2==0){ number = number / 2; count++; printf("result %d divided %d times",number,count); // wait until the user hit 'e' while (getchar()!='e'){; return 0;
Rules and recommendations (Industrial Strength C++ Mats Henricson, Erik Nyquist) Do not change a loop variable inside a for-loop block. Update loop variables close to where the loop-condition is specified. Use a for loop if the loop variable is updated on exit from the block AFTER the loop condition has been checked. Use a do-while loop if the loop will execute at least once and if the loop variable is updated BEFORE the condition is checked. Use a while loop if the loop variable is updated on entry to the block AFTER the loop condition has been checked. All flow control primitives (if, else, while, for, do, switch and case) should be followed by a block, even if it is empty. Statements following a case label should be terminated by a statement that exits the switchstatement. All switch statements should have a defaultclause. Use break and continue instead of goto.
Read/Write from/to console printf() - print to the console (standard output) / puts() #include <stdio.h> int main() { int nr = 5; float nrf = 3.14; char c = 's'; char str[] = "abc"; printf("%d %f %c %s", nr, nrf, c, str); return 0; A format specifier follows this prototype: %[flags][width][.precision][length]specifier specifier: d,s,p (decimal, string, pointer) scanf() - read from the command line / fgets() / gets() int main() { int nr; float f; printf("enter a decimal number:"); //read from the command line and store the value in nr scanf("%d", &nr); printf("the number is:%d \n", nr); printf("enter a float:"); if (scanf("%f", &f) == 0) { printf("error: Not a float:"); else { printf("the number is:%f", f); //wait until user enters 'e' while(getchar()!='e'); return 0; A format specifier for scanf follows this prototype: %[*][width][length]specifier Specifier: d, f, s (decimal, floating-point, string)
First calculator Problem statement A teacher needs a program for students who learn or use rational numbers. The program shall help students to make basic arithmetic operations. #include <stdio.h> int main() { int totalm = 0; int totaln = 1; int m; int n; while (1) { printf("enter m, then n to add\n"); scanf("%d", &m); scanf("%d", &n); totalm = totalm * n + m * totaln; totaln = totaln * n; printf("total: %d/%d\n", totalm, totaln); return 0; Using struct #include <stdio.h> typedef struct{ int m,n; Rational; int main() { Rational total= {0,1; int m;int n; while (1) { printf("enter m, then n to add\n"); scanf("%d", &m); scanf("%d", &n); total.m = total.m * n + m * total.n; total.n = total.n * n; printf("total: %d/%d\n", total.m, total.n); return 0;
Outline Introduction - OOP C Programming language syntax statements data types functions