SlideShare una empresa de Scribd logo
1 de 80
1 Object Oriented ProgrammingDevelopment
2 What are we doing today? Introduction of: the lecturer Objects Basic Terminology C++ the module
3 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object An object is like a black box.  The internal details are hidden.
4 What is an object? Tangible Things    as a car, printer, ... Roles                   as employee, boss, ... Incidents              as flight, overflow, ... Interactions          as contract, sale, ... Specifications        as colour, shape, …
5 So, what are objects? an object represents an individual, identifiable item, unit, or entity, either real or abstract, with a well-defined role in the problem domain. Or An "object" is anything to which a concept applies. Etc.
6 Why do we care about objects? Modularity - large software projects can be split up in smaller pieces. Reuseability - Programs can be assembled from pre-written software components. Extensibility - New software components can be written or developed from existing ones.
Example: The Person class #include<string> #include<iostream> class Person{        char name[20];      int yearOfBirth; public:       void displayDetails() {                   cout << name << " born in "                        << yearOfBirth << endl;                   }      //... }; private  data public  processes
8 The two parts of an object           Object = Data + Methods or to say the same differently: An object has the responsibility to know and the responsibility to do. = +
9 Basic Terminology Abstraction is the representation of the essential features of an object. These are ‘encapsulated’ into an abstract data type. Encapsulation is the practice of including in an object everything it needs hidden from other objects. The internal state is usually not accessible by other objects.
10 Basic Terminology:Inheritance Inheritance means that one class inherits the characteristics of another class.This is also called a “is a” relationship: A car is a vehicle A dog is an animal A teacher is a person
11 Basic Terminology:Polymorphism Polymorphism means “having many forms”. It allows different objects to respond to the same message in different ways, the response specific to the type of the object. E.g. the message displayDetails() of the Person class should give different results when send to a Student object (e.g. the enrolment number).
12 Basic Terminology:Aggregation Aggregation describes a “has a” relationship. One object is a part of another object.  We distinguish between composite aggregation (the composite “owns” the part) and shared aggregation (the part is shared by more then one composite). A car has wheels.
13 Basic Terminology:Behaviour and Messages The most important aspect of an object is its behaviour (the things it can do). A behaviour is initiated by sending a message to the object (usually by calling a method).
14 The two steps of Object Oriented Programming Making Classes: Creating, extending or reusing abstract data types. Making Objects interact: Creating objects from abstract data types and defining their relationships.
15 Module Outline Introduction The non object oriented basics Classes Design Approaches Testing Inheritance Aggregation Polymorphism Multifile Development
16 Today: Extensive analysis of an example program. Data types, operators, functions and I/O. Arrays, strings, pointers Control structures.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } }
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } The header of the file. Should contain general information as file name, author, description, etc. The compiler ignores these lines (see next slide).
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } This is a C++ comment. Lines starting with // are ignored by the compiler. Also ignored is text enclosed by /* and */
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } A pre-processor directive. Lines starting with a # are interpreted by a pre-processor before the compiler processes the file. Other important directives are #define, #ifdef, #endif, #pragma, ...
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p); cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {  cout << “*” << endl;          } } In this example we include the file iostream.h into the program. iostream.h defines classes and objects related to input and output. We need it here because  cout is declared there.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p); cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {  cout << “*” << endl;          } } Observation:  cout is not a keyword of C++ but an identifier defined in the iostream library.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } A function prototype.  In this line the compiler is told about a function with the name doSomething and its signature.  The function here has one parameter (int) and no return value (void).
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } Also global variables and class declarations usually come here.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } The main function is the entry point of a C++ program. Each C++ program must have exactly one main() method.  The return value of main() is an int. This value is passed to the system which invoked the C++ program.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } The code which implements the main function is enclosed in { and }.  Statements enclosed in { and } are called a block.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  { int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } We declare a variable p of type int. Other important data types of C++ are char, unsigned int, long, unsigned long, float, double, bool. The variable p is immediately initialised with the value 7.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7; doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } The function doSomething() is called with the parameter p.
A typical C++ program This statement prints the string “I have something done.” to the screen.  The “stream manipulator” endl outputs a newline and then “flushes the output buffer”. // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p); cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } }
A typical C++ program Functions with a return value which is not void use the return keyword in order to return their value to the calling function. In the special situation here, the main() method has no calling function. The value 0 is passed back to system when the program is finished. Usually 0 means that the program worked correctly. // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl; return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } }
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } } The implementation of the previously defined function doSomething.
A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main()  {    int p = 7;    doSomething(p);    cout << “I have something done.” << endl;    return 0; } void doSomething(int p) {     for( int i = 0; i < p; i++ ) {          cout << “*” << endl;          } }
33 Basics of C++ - data types Some Fundamental data types: char	characters: ’a’, ’b’, ’’, ’’, ’7’ int		integers: 3, 6883, -5, 0 double	floating point numbers: 3.14, 7e9 bool 	true or false.	 Also: float, long, unsigned long, short, unsigned char, wchar_t
34 Basics of C++ - variables Declaring variables in a program: char a; int b;  double c; Assignment: b = 4; a = 'w’; c = -3.777; int x = 78;
35 Basics of C++ - variables Constants: const double PI=3.1415926; const int MAXBUFFER=20; Note: the const keyword is also used for method parameters, methods and return values (later)
36 Basics of C++ - operators Arithmetic operators: +, -, *, /, % Comparison: ==, !=, <, >, >=, <= Logical: &&, ||, ! Assignment: = Bitwise: &, |, ~,^ Shortcuts: +=, *=, ^=, (etc.) Other: <<, >>, ?  :, ->, ., ,
37 Basics of C++ - operators The unary operators ++ and --: ++      	increment by 1 --     		decrement by 1  The language C++ got its name by this operator! Note, that i++ and ++i have different behaviour […]
38 Basics of C++ - functions int someFunction(double f, char c) {     // …} Name Body ParameterList Return Type
39 Basics of C++ - functions Please note, that a function is specified by the name and the parameter types. The following functions are all different: int exampleFunction(int i, char c); int exampleFunction(double f); int exampleFunction(); int exampleFunction(char c, int i);
40 Basics of C++ - functions Pass by reference, example: void square(int &v) { v = v * v; } In contrast, pass by value: int square(int v) { return v * v; } The parameter v is not copied.
41 Basics of C++: I/O For output use cout, e.g. cout << “The result is: “ << result << endl; For input use cin, e.g. cin >> x; Note that iostream.h must be included via  #include <iostream.h>
42 Basics of C++ - arrays Declaration: int numbers[10]; Declaration & Initialisation:  int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19 }; Access:  numbers[6] = 2483; cout << “The fourth prime is “ << primes[4];
43 Basics of C++ - Strings There aren’t any strings in C++.
44 Basics of C++ - Strings There aren’t any strings in C++. O.k., that’s only half of the truth. In fact, by convention, strings are represented in C++ as ’’ terminated arrays of characters. In addition, the file string.h declares useful string manipulating functions, e.g. strcpy, strlen which deal with ’’ terminated character arrays.
45 Basics of C++ - pointer A pointer points to a memory location which contains data of a particular type. The contents of a pointer is the address of some data Declaration:  int *p;  double *aDoublePointer;
46 Basics of C++ - pointer In C++ pointer and arrays are strongly related (“array = pointer + memory”). int primes[] = {2, 3, 5, 7, 11 }; int *aPr = primes; aPr++; cout << “The third prime is “ << *(aPr + 2);  pointer arithmetic The * operator accesses the data on the memory address
47 Control Structures - Decisions The if statement: if ( x > 0 ) {      cout << “positive”; } else {      cout << “negative or zero”; }
48 Control Structures - Decisions The switch statement - example: int x; cout << "Enter choice (1, 2, or 3)"; cin >> x; switch(x) {    case 1: doThis(); break;    case 2: doThat(); break;    case 3: doSomethingElse(); break;    default: cout << "Sorry, invalid Input"; }
49 Control Structures - Iteration The for loop: for(k = 0; k < 10; k++ ) {     cout << “The square of  “ << k << “ is “           << k * k << endl;    } Terminating condition Start condition Action taking place atthe end of each iteration
50 Control Structures - Iteration The while loop: while ( condition ) {         // do something        } Equivalent to:  for( ; condition ; ) {       // do something      }
51 Control structures -                           do … while The do … while loop: do {      // something } while( condition); Equivalent to: // something while( condition) {       // something      }
52 Control Structures And finally:  Yes, C++ has a goto.                            Don’t use it.
53 Module Outline Introduction The non object oriented basics Classes Design Approaches Testing Inheritance Aggregation Polymorphism Multifile Development
54 Today: Control structures. Pointers. Classes Objects
55 Basics of C++ - pointer A pointer points to a memory location which contains data of a particular type. The contents of a pointer is the address of some data Declaration:  int *p;  double *aDoublePointer; 2.73817
56 Again: Basics of C++ - arrays Declaration: int numbers[10]; Declaration & Initialisation:  int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19 }; Access:  numbers[6] = 2483; cout << “The fourth prime is “ << primes[4];
57 Basics of C++ - pointer In C++ pointer and arrays are strongly related (“array = pointer + memory”). int primes[] = {2, 3, 5, 7, 11 }; int *aPr = primes; cout << “The third prime is “ << *(aPr + 3);  The same as primes[3] The * operator accesses the data on the memory address
58 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object An object is like a black box.  The internal details are hidden.
59 The two steps of Object Oriented Programming Making Classes: Creating, extending or reusing abstract data types. Making Objects interact: Creating objects from abstract data types and defining their relationships.
Example: The Creature class class Creature {     private:    int yearOfBirth; public:       void setYearOfBirth(year) {             yearOfBirth = year;             }    int getYearOfBirth() {              return yearOfBirth;             }  }; born1997
Example: The Creature class class Creature{     private: int yearOfBirth; public:    void setYearOfBirth(year) {             yearOfBirth = year;             }    int getYearOfBirth() {              return yearOfBirth;             }  }; The definition of a  class: ,[object Object]
private attributes.
public methods.
the ; at the end,[object Object]
Example: The Creature class class Creature { private:    int yearOfBirth; public:       void setYearOfBirth(year) {             yearOfBirth = year;             }    int getYearOfBirth() {              return yearOfBirth;             }  }; This class has two (public) methods. One to set the attribute value and the other to retrieve the attribute value.
Example: The Creature class class Creature {     private:    int yearOfBirth; public:       void setYearOfBirth(year);    int getYearOfBirth(); }; void Creature::setYearOfBirth {             yearOfBirth = year;             } int Creature::getYearOfBirth() {              return yearOfBirth;             }  Note that unless the methods are very short, declaration and implementation is usually separated. The declaration goes into a header file (.h), the implementation in a .cpp file.
Example: The Creature class class Creature { private:    int yearOfBirth; public:       void setYearOfBirth(year) {             yearOfBirth = year;             } int getYearOfBirth() {              return yearOfBirth;             }  }; This method is an example for a ‘modifier’ method. It modifies the attribute. The method changes the state of the object.
Example: The Creature class class Creature { private:    int yearOfBirth; public:    void setYearOfBirth(year) {             yearOfBirth = year;             }    int getYearOfBirth() {              return yearOfBirth;             }  }; This method is an example for a ‘selector’ method. It returns information about the attribute but does not change the state of the object.
67 Classes & Objects What may be different for all objects in a class, and what remains the same? All the objects in a class may have different attribute values (state data), but their allowed behaviours are all the same. So a class is a blueprint for objects
68 Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour
69 Instantiating Objects An object is instantiated just like any other data type: int x; char y; Creature z;  Declaring z of type ‘creature’  means we have generated an object with the attributes and methods of the class.
70 Multiple Objects Of course we can create many objects of the same class: Creature myDog; Creature theMilkman; Creature myBestFriend; Creates three objects.
71 Sending Messages /                  Calling Methods. A message is send to an object by calling a method of this object. Use the . (dot) for calling a method of an object. int k;  k =  theMilkman.getYearOfBirth(); myDog.setYearOfBirth(1998); Messages are sent to my dog and the milkman.
72 Back to the Instantiation... An object is instantiated just like any other data type: int x; char y; Creature z;  Here the “default constructor” of the Creature class is automatically called. If we don’t like this we can specify constructors explicitly!
The Creature class with a user defined default constructor. class Creature {     private:    int yearOfBirth; public:   // …   Creature() {        yearOfBirth = 1970;       cout << “Hello.”;       }    }; The syntax for a constructoris similar as for a method, but: ,[object Object]
It has no return value.,[object Object]
The Creature with a copy constructor. Example: Creature myDog(1995); Creature myCat(myDog); creates a cat of the same age as the dog. class Creature {     private:    int yearOfBirth; public:   // …   Creature(Creature & otherCreature) {        yearOfBirth =           otherCreature.getYearOfBirth();       }    };
76 Constructors - summary A constructor is always called when an object is created. We can define our own constructors (Note: a class can have more than one constructor). If an object is copied from another object then the copy constructor is called.
77 Again: Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour
78 Again: Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour But: We can give a class state and behaviour with the keyword static!

Más contenido relacionado

La actualidad más candente

C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
IIUM
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
IIUM
 

La actualidad más candente (20)

PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
basics of c++
basics of c++basics of c++
basics of c++
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
 
Deep C
Deep CDeep C
Deep C
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 

Destacado

Lecture 02 terminology of database
Lecture 02 terminology of  databaseLecture 02 terminology of  database
Lecture 02 terminology of database
emailharmeet
 
Cardinality and participation constraints
Cardinality and participation constraintsCardinality and participation constraints
Cardinality and participation constraints
Nikhil Deswal
 
Autobiografia cleo
Autobiografia cleoAutobiografia cleo
Autobiografia cleo
tony
 
Thang danh gia dinh duong trong dat
Thang danh gia dinh duong trong datThang danh gia dinh duong trong dat
Thang danh gia dinh duong trong dat
cinnamonVY
 
Игры в обучении в и оценке эффективности обучения
Игры в обучении в и оценке эффективности обученияИгры в обучении в и оценке эффективности обучения
Игры в обучении в и оценке эффективности обучения
Dmitri Kunin
 
Calaveras
CalaverasCalaveras
Calaveras
tony
 

Destacado (20)

Lecture 02 terminology of database
Lecture 02 terminology of  databaseLecture 02 terminology of  database
Lecture 02 terminology of database
 
Relationship in database
Relationship in databaseRelationship in database
Relationship in database
 
Laravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureLaravel.IO A Use-Case Architecture
Laravel.IO A Use-Case Architecture
 
Cardinality and participation constraints
Cardinality and participation constraintsCardinality and participation constraints
Cardinality and participation constraints
 
Use Case Modeling
Use Case ModelingUse Case Modeling
Use Case Modeling
 
Cuenta
CuentaCuenta
Cuenta
 
Autobiografia cleo
Autobiografia cleoAutobiografia cleo
Autobiografia cleo
 
The Member--Centric Association Configuring Your Organization for Membership...
The Member--Centric Association Configuring Your Organization  for Membership...The Member--Centric Association Configuring Your Organization  for Membership...
The Member--Centric Association Configuring Your Organization for Membership...
 
Assignment#4 gorosito
Assignment#4 gorositoAssignment#4 gorosito
Assignment#4 gorosito
 
Thang danh gia dinh duong trong dat
Thang danh gia dinh duong trong datThang danh gia dinh duong trong dat
Thang danh gia dinh duong trong dat
 
Peniaian formatif
Peniaian formatifPeniaian formatif
Peniaian formatif
 
http://taiwanheart.ning.com
http://taiwanheart.ning.comhttp://taiwanheart.ning.com
http://taiwanheart.ning.com
 
El pueblo quezon city
El pueblo quezon cityEl pueblo quezon city
El pueblo quezon city
 
Как презентовать так, что бы слушатели не заснули!
Как презентовать так, что бы слушатели не заснули!Как презентовать так, что бы слушатели не заснули!
Как презентовать так, что бы слушатели не заснули!
 
Ley 769 2002
Ley 769 2002Ley 769 2002
Ley 769 2002
 
WordBeach @kurudrive
WordBeach @kurudriveWordBeach @kurudrive
WordBeach @kurudrive
 
Featureadmin
FeatureadminFeatureadmin
Featureadmin
 
Игры в обучении в и оценке эффективности обучения
Игры в обучении в и оценке эффективности обученияИгры в обучении в и оценке эффективности обучения
Игры в обучении в и оценке эффективности обучения
 
Calaveras
CalaverasCalaveras
Calaveras
 
Hepatitis a
Hepatitis aHepatitis a
Hepatitis a
 

Similar a Revision Lecture

香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
biyu
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
Ahammed Alamin
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
SURBHI SAROHA
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 

Similar a Revision Lecture (20)

C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Flutter Festival IIT Goa: Session 1
Flutter Festival IIT Goa: Session 1Flutter Festival IIT Goa: Session 1
Flutter Festival IIT Goa: Session 1
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
C++
C++C++
C++
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Lecture 3 c++
Lecture 3 c++Lecture 3 c++
Lecture 3 c++
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 

Más de emailharmeet

Más de emailharmeet (18)

Lecture 10 distributed database management system
Lecture 10   distributed database management systemLecture 10   distributed database management system
Lecture 10 distributed database management system
 
Lecture 09 dblc centralized vs decentralized design
Lecture 09   dblc centralized vs decentralized designLecture 09   dblc centralized vs decentralized design
Lecture 09 dblc centralized vs decentralized design
 
Lecture 09 dblc centralized vs decentralized design
Lecture 09   dblc centralized vs decentralized designLecture 09   dblc centralized vs decentralized design
Lecture 09 dblc centralized vs decentralized design
 
Lecture 08 distributed dbms
Lecture 08 distributed dbmsLecture 08 distributed dbms
Lecture 08 distributed dbms
 
Lecture 07 relational database management system
Lecture 07 relational database management systemLecture 07 relational database management system
Lecture 07 relational database management system
 
Lecture 06 relational algebra and calculus
Lecture 06 relational algebra and calculusLecture 06 relational algebra and calculus
Lecture 06 relational algebra and calculus
 
Testing lecture after lec 4
Testing lecture after lec 4Testing lecture after lec 4
Testing lecture after lec 4
 
Lab 1
Lab 1Lab 1
Lab 1
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Course File c++
Course File c++Course File c++
Course File c++
 
Lecture 05 dblc
Lecture 05 dblcLecture 05 dblc
Lecture 05 dblc
 
Assignmnet 1
Assignmnet 1Assignmnet 1
Assignmnet 1
 
Lecture 04 normalization
Lecture 04 normalization Lecture 04 normalization
Lecture 04 normalization
 
Lecture 03 data abstraction and er model
Lecture 03 data abstraction and er modelLecture 03 data abstraction and er model
Lecture 03 data abstraction and er model
 
Lecture 01 introduction to database
Lecture 01 introduction to databaseLecture 01 introduction to database
Lecture 01 introduction to database
 
Lecture 00 introduction to course
Lecture 00 introduction to courseLecture 00 introduction to course
Lecture 00 introduction to course
 
Syllabus mca 2 rdbms i
Syllabus mca 2 rdbms iSyllabus mca 2 rdbms i
Syllabus mca 2 rdbms i
 

Revision Lecture

  • 1. 1 Object Oriented ProgrammingDevelopment
  • 2. 2 What are we doing today? Introduction of: the lecturer Objects Basic Terminology C++ the module
  • 3. 3 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object An object is like a black box. The internal details are hidden.
  • 4. 4 What is an object? Tangible Things as a car, printer, ... Roles as employee, boss, ... Incidents as flight, overflow, ... Interactions as contract, sale, ... Specifications as colour, shape, …
  • 5. 5 So, what are objects? an object represents an individual, identifiable item, unit, or entity, either real or abstract, with a well-defined role in the problem domain. Or An "object" is anything to which a concept applies. Etc.
  • 6. 6 Why do we care about objects? Modularity - large software projects can be split up in smaller pieces. Reuseability - Programs can be assembled from pre-written software components. Extensibility - New software components can be written or developed from existing ones.
  • 7. Example: The Person class #include<string> #include<iostream> class Person{ char name[20]; int yearOfBirth; public: void displayDetails() { cout << name << " born in " << yearOfBirth << endl; } //... }; private data public processes
  • 8. 8 The two parts of an object Object = Data + Methods or to say the same differently: An object has the responsibility to know and the responsibility to do. = +
  • 9. 9 Basic Terminology Abstraction is the representation of the essential features of an object. These are ‘encapsulated’ into an abstract data type. Encapsulation is the practice of including in an object everything it needs hidden from other objects. The internal state is usually not accessible by other objects.
  • 10. 10 Basic Terminology:Inheritance Inheritance means that one class inherits the characteristics of another class.This is also called a “is a” relationship: A car is a vehicle A dog is an animal A teacher is a person
  • 11. 11 Basic Terminology:Polymorphism Polymorphism means “having many forms”. It allows different objects to respond to the same message in different ways, the response specific to the type of the object. E.g. the message displayDetails() of the Person class should give different results when send to a Student object (e.g. the enrolment number).
  • 12. 12 Basic Terminology:Aggregation Aggregation describes a “has a” relationship. One object is a part of another object. We distinguish between composite aggregation (the composite “owns” the part) and shared aggregation (the part is shared by more then one composite). A car has wheels.
  • 13. 13 Basic Terminology:Behaviour and Messages The most important aspect of an object is its behaviour (the things it can do). A behaviour is initiated by sending a message to the object (usually by calling a method).
  • 14. 14 The two steps of Object Oriented Programming Making Classes: Creating, extending or reusing abstract data types. Making Objects interact: Creating objects from abstract data types and defining their relationships.
  • 15. 15 Module Outline Introduction The non object oriented basics Classes Design Approaches Testing Inheritance Aggregation Polymorphism Multifile Development
  • 16. 16 Today: Extensive analysis of an example program. Data types, operators, functions and I/O. Arrays, strings, pointers Control structures.
  • 17. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } }
  • 18. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } The header of the file. Should contain general information as file name, author, description, etc. The compiler ignores these lines (see next slide).
  • 19. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } This is a C++ comment. Lines starting with // are ignored by the compiler. Also ignored is text enclosed by /* and */
  • 20. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } A pre-processor directive. Lines starting with a # are interpreted by a pre-processor before the compiler processes the file. Other important directives are #define, #ifdef, #endif, #pragma, ...
  • 21. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } In this example we include the file iostream.h into the program. iostream.h defines classes and objects related to input and output. We need it here because cout is declared there.
  • 22. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } Observation: cout is not a keyword of C++ but an identifier defined in the iostream library.
  • 23. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } A function prototype. In this line the compiler is told about a function with the name doSomething and its signature. The function here has one parameter (int) and no return value (void).
  • 24. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } Also global variables and class declarations usually come here.
  • 25. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } The main function is the entry point of a C++ program. Each C++ program must have exactly one main() method. The return value of main() is an int. This value is passed to the system which invoked the C++ program.
  • 26. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } The code which implements the main function is enclosed in { and }. Statements enclosed in { and } are called a block.
  • 27. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } We declare a variable p of type int. Other important data types of C++ are char, unsigned int, long, unsigned long, float, double, bool. The variable p is immediately initialised with the value 7.
  • 28. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } The function doSomething() is called with the parameter p.
  • 29. A typical C++ program This statement prints the string “I have something done.” to the screen. The “stream manipulator” endl outputs a newline and then “flushes the output buffer”. // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } }
  • 30. A typical C++ program Functions with a return value which is not void use the return keyword in order to return their value to the calling function. In the special situation here, the main() method has no calling function. The value 0 is passed back to system when the program is finished. Usually 0 means that the program worked correctly. // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } }
  • 31. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } } The implementation of the previously defined function doSomething.
  • 32. A typical C++ program // FileID: hello.cpp // Title: The program doing something #include <iostream.h> void doSomething(int p); int main() { int p = 7; doSomething(p); cout << “I have something done.” << endl; return 0; } void doSomething(int p) { for( int i = 0; i < p; i++ ) { cout << “*” << endl; } }
  • 33. 33 Basics of C++ - data types Some Fundamental data types: char characters: ’a’, ’b’, ’’, ’’, ’7’ int integers: 3, 6883, -5, 0 double floating point numbers: 3.14, 7e9 bool true or false. Also: float, long, unsigned long, short, unsigned char, wchar_t
  • 34. 34 Basics of C++ - variables Declaring variables in a program: char a; int b; double c; Assignment: b = 4; a = 'w’; c = -3.777; int x = 78;
  • 35. 35 Basics of C++ - variables Constants: const double PI=3.1415926; const int MAXBUFFER=20; Note: the const keyword is also used for method parameters, methods and return values (later)
  • 36. 36 Basics of C++ - operators Arithmetic operators: +, -, *, /, % Comparison: ==, !=, <, >, >=, <= Logical: &&, ||, ! Assignment: = Bitwise: &, |, ~,^ Shortcuts: +=, *=, ^=, (etc.) Other: <<, >>, ? :, ->, ., ,
  • 37. 37 Basics of C++ - operators The unary operators ++ and --: ++ increment by 1 -- decrement by 1 The language C++ got its name by this operator! Note, that i++ and ++i have different behaviour […]
  • 38. 38 Basics of C++ - functions int someFunction(double f, char c) { // …} Name Body ParameterList Return Type
  • 39. 39 Basics of C++ - functions Please note, that a function is specified by the name and the parameter types. The following functions are all different: int exampleFunction(int i, char c); int exampleFunction(double f); int exampleFunction(); int exampleFunction(char c, int i);
  • 40. 40 Basics of C++ - functions Pass by reference, example: void square(int &v) { v = v * v; } In contrast, pass by value: int square(int v) { return v * v; } The parameter v is not copied.
  • 41. 41 Basics of C++: I/O For output use cout, e.g. cout << “The result is: “ << result << endl; For input use cin, e.g. cin >> x; Note that iostream.h must be included via #include <iostream.h>
  • 42. 42 Basics of C++ - arrays Declaration: int numbers[10]; Declaration & Initialisation: int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19 }; Access: numbers[6] = 2483; cout << “The fourth prime is “ << primes[4];
  • 43. 43 Basics of C++ - Strings There aren’t any strings in C++.
  • 44. 44 Basics of C++ - Strings There aren’t any strings in C++. O.k., that’s only half of the truth. In fact, by convention, strings are represented in C++ as ’’ terminated arrays of characters. In addition, the file string.h declares useful string manipulating functions, e.g. strcpy, strlen which deal with ’’ terminated character arrays.
  • 45. 45 Basics of C++ - pointer A pointer points to a memory location which contains data of a particular type. The contents of a pointer is the address of some data Declaration: int *p; double *aDoublePointer;
  • 46. 46 Basics of C++ - pointer In C++ pointer and arrays are strongly related (“array = pointer + memory”). int primes[] = {2, 3, 5, 7, 11 }; int *aPr = primes; aPr++; cout << “The third prime is “ << *(aPr + 2); pointer arithmetic The * operator accesses the data on the memory address
  • 47. 47 Control Structures - Decisions The if statement: if ( x > 0 ) { cout << “positive”; } else { cout << “negative or zero”; }
  • 48. 48 Control Structures - Decisions The switch statement - example: int x; cout << "Enter choice (1, 2, or 3)"; cin >> x; switch(x) { case 1: doThis(); break; case 2: doThat(); break; case 3: doSomethingElse(); break; default: cout << "Sorry, invalid Input"; }
  • 49. 49 Control Structures - Iteration The for loop: for(k = 0; k < 10; k++ ) { cout << “The square of “ << k << “ is “ << k * k << endl; } Terminating condition Start condition Action taking place atthe end of each iteration
  • 50. 50 Control Structures - Iteration The while loop: while ( condition ) { // do something } Equivalent to: for( ; condition ; ) { // do something }
  • 51. 51 Control structures - do … while The do … while loop: do { // something } while( condition); Equivalent to: // something while( condition) { // something }
  • 52. 52 Control Structures And finally: Yes, C++ has a goto. Don’t use it.
  • 53. 53 Module Outline Introduction The non object oriented basics Classes Design Approaches Testing Inheritance Aggregation Polymorphism Multifile Development
  • 54. 54 Today: Control structures. Pointers. Classes Objects
  • 55. 55 Basics of C++ - pointer A pointer points to a memory location which contains data of a particular type. The contents of a pointer is the address of some data Declaration: int *p; double *aDoublePointer; 2.73817
  • 56. 56 Again: Basics of C++ - arrays Declaration: int numbers[10]; Declaration & Initialisation: int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19 }; Access: numbers[6] = 2483; cout << “The fourth prime is “ << primes[4];
  • 57. 57 Basics of C++ - pointer In C++ pointer and arrays are strongly related (“array = pointer + memory”). int primes[] = {2, 3, 5, 7, 11 }; int *aPr = primes; cout << “The third prime is “ << *(aPr + 3); The same as primes[3] The * operator accesses the data on the memory address
  • 58. 58 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object An object is like a black box. The internal details are hidden.
  • 59. 59 The two steps of Object Oriented Programming Making Classes: Creating, extending or reusing abstract data types. Making Objects interact: Creating objects from abstract data types and defining their relationships.
  • 60. Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; born1997
  • 61.
  • 64.
  • 65. Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This class has two (public) methods. One to set the attribute value and the other to retrieve the attribute value.
  • 66. Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year); int getYearOfBirth(); }; void Creature::setYearOfBirth { yearOfBirth = year; } int Creature::getYearOfBirth() { return yearOfBirth; } Note that unless the methods are very short, declaration and implementation is usually separated. The declaration goes into a header file (.h), the implementation in a .cpp file.
  • 67. Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This method is an example for a ‘modifier’ method. It modifies the attribute. The method changes the state of the object.
  • 68. Example: The Creature class class Creature { private: int yearOfBirth; public: void setYearOfBirth(year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } }; This method is an example for a ‘selector’ method. It returns information about the attribute but does not change the state of the object.
  • 69. 67 Classes & Objects What may be different for all objects in a class, and what remains the same? All the objects in a class may have different attribute values (state data), but their allowed behaviours are all the same. So a class is a blueprint for objects
  • 70. 68 Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour
  • 71. 69 Instantiating Objects An object is instantiated just like any other data type: int x; char y; Creature z; Declaring z of type ‘creature’ means we have generated an object with the attributes and methods of the class.
  • 72. 70 Multiple Objects Of course we can create many objects of the same class: Creature myDog; Creature theMilkman; Creature myBestFriend; Creates three objects.
  • 73. 71 Sending Messages / Calling Methods. A message is send to an object by calling a method of this object. Use the . (dot) for calling a method of an object. int k; k = theMilkman.getYearOfBirth(); myDog.setYearOfBirth(1998); Messages are sent to my dog and the milkman.
  • 74. 72 Back to the Instantiation... An object is instantiated just like any other data type: int x; char y; Creature z; Here the “default constructor” of the Creature class is automatically called. If we don’t like this we can specify constructors explicitly!
  • 75.
  • 76.
  • 77. The Creature with a copy constructor. Example: Creature myDog(1995); Creature myCat(myDog); creates a cat of the same age as the dog. class Creature { private: int yearOfBirth; public: // … Creature(Creature & otherCreature) { yearOfBirth = otherCreature.getYearOfBirth(); } };
  • 78. 76 Constructors - summary A constructor is always called when an object is created. We can define our own constructors (Note: a class can have more than one constructor). If an object is copied from another object then the copy constructor is called.
  • 79. 77 Again: Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour
  • 80. 78 Again: Objects & Classes A class is defined by: A Unique Name Attributes Methods An object is defined by: Identity State Behaviour But: We can give a class state and behaviour with the keyword static!
  • 81. Example: The Creature class class Creature { private: int yearOfBirth; static int numberOfAllCreatures = 0; public: Creature() { // Constructor - counts the creatures. numberOfAllCreatures++; } static int getNumberOfAllCreatures() { return numberOfAllCreatures; } }; Note that all objects share the same value of the “class attribute” numberOfAllCreatures.
  • 82. 80 Summary. A class is a blueprint for an object. Objects are created similar to other data types (int, char, …). The construction of an object can be defined by the user. Messages are sent to an object by calling a method. static messes the concept of classes and objects (but is nevertheless useful).