Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
OOP Abstraction Classes Class Members: Properties & Methods Instance (object) Encapsulation Interfaces Inheritance Composition Polymorphism Using Inheritance.
Chapter 12: Inheritance and Composition
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
C++ Classes & Data Abstraction
1/03/09 De 89 à 98. 1/03/09 De 89 à 98 1/03/09 De 89 à 98.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Markov Chains Ali Jalali. Basic Definitions Assume s as states and s as happened states. For a 3 state Markov model, we construct a transition matrix.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
1 Composition A whole-part relationship (e.g. Dog-Tail) Whole and part objects have same lifetime –Whole creates instance of part in its constructor In.
7M701 1 Class Diagram advanced concepts. 7M701 2 Characteristics of Object Oriented Design (OOD) objectData and operations (functions) are combined 
C++ data types. Structs vs. Classes C++ Classes.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Inheritance and Composition.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 12: Inheritance and Composition.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 13: Inheritance and Composition.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
CMSC 202 Lesson 16 Inheritance. Warmup Identify which constructor each of the following use (default, non-default, copy) MyClass a; MyClass b(a); MyClass.
Objected Oriented Programming & Design JAVA Shishir Gupta (704) (704)
Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design Guidelines.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
1 COMP313A Programming Languages Object Oriented Progamming Languages (3)
A little bit of UML Csaba Veres. UML A de facto standard for OO analysis and design Many components class diagrams use cases interaction diagrams...
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Department of Computer Science Data Structures Using C++ 2E Chapter 2 Object-Oriented Design (OOD) and C++  Learn about inheritance  Learn about derived.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 13: Inheritance and Composition.
CITA 342 Section 1 Object Oriented Programming (OOP)
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Inclusive planet the global social library for the visually impaired.
1.7 Linear Independence. in R n is said to be linearly independent if has only the trivial solution. in R n is said to be linearly dependent if there.
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
CLASS DIAGRAMS A classy approach to objects. The Basic Class Diagram  Class Name  Attributes (- indicates private each would have properties or accessor/mutator.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
1 Welcome Alireza Humber College Lecture 1 Game 540 Alireza
。 33 投资环境 3 开阔视野 提升竞争力 。 3 嘉峪关市概况 。 3 。 3 嘉峪关是一座新兴的工业旅游城市,因关得名,因企设市,是长城文化与丝路文化交 汇点,是全国唯一一座以长城关隘命名的城市。嘉峪关关城位于祁连山、黑山之间。 1965 年建市,下辖雄关区、镜铁区、长城区, 全市总面积 2935.
Construction Lecture Oo21 Gymnastics System Example Cont’d.
DOMAIN CLASSES – PART 1 BTS430 Systems Analysis and Design using UML.
Class Relationships in C++
Unified Modeling Language (UML)
A First C++ Class – a Circle
Object-Orientated Programming
CS212: Object Oriented Analysis and Design
Object-oriented programming
Modeling Classes with UML
Overloading the << operator
Software Engineering System Modeling Extra examples Dr.Doaa Sami
Introduction to Programming
Diana CSORBA - Lector Dr
Chapter 11: Inheritance and Composition

Operator Overloading I
Inheritance -I.
Eighth step for Learning C++ Programming
COP 3330 Object-oriented Programming in C++
Overloading the << operator
C++ data types.
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
ADVANCED OBJECT-ORIENTED PROGRAMMING
Inheritance in C++ Inheritance Protected Section
Presentation transcript:

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

2Programming IIObject-Oriented Programming Course #4 Agenda Classes (continued) Friends Objects Construction and destruction of objects Class Relationships Association Aggregation Composition Inheritance

3Programming IIObject-Oriented Programming Friends (I) DEFINITION [Friend functions] Friend functions are functions that are not members of one class, yet they have access to private members (data + function) declared in that class. DEFINITION [Friend class] If class X is friend class of class Y, then all member functions of class X are friend functions (i.e. have access to private members) of class Y. class Matrix { /* declarations */ } ; class Vector {/* declarations */ }; Define a function that: Vector x Matrix  Vector Rationale: functions need access to private members of one class Solution: make those functions members of the class What happens if one function need to have access to private members of 2 ore more classes? It can be member of only one class ;( Friends – help us to do this ;) // a class defined in an external library; // no access to implementation is available class ostream { public: ostream& operator<<(int x); } ; class Vector {/* declarations */ }; // our class void f(ostream& out, Vector& v) { out << v; // we should add a new member function // operator<<(Vector&); // but, ostream class cannot be changed }

4Programming IIObject-Oriented Programming Friends (II) It’s not relevant the access control modifier (private, public, protected) used to declare a friend function/class; Friend functions are not member of the class for which they are friend REMARK: One of the key principle OO is data hiding (encapsulation), but sometimes is to restrictive and needs to be “broken”  Not recommendable to use friends; use only if it’s impossible to solve the problem otherwise friend ftype fname(arg_list); friend class X; Friends can be either functions member of another class or global functions. Syntax:

5Programming IIObject-Oriented Programming Friends (III) Example: class Matrix; // Forward declaration class Vector { float v[4]; public: Vector(float v0=0, float v1=0, float v2=0, float v3=0); friend Vector multiply(const Matrix&, const Vector&); }; class Matrix { Vector rows[4]; friend Vector multiply(const Matrix&, const Vector&); }; More examples: see operator overloading Finding friends: declared before or identifiable by argument type Friendship is NOT reflexive nor transitive Friendship is not inherited Rights and restrictions vs. various function types => ActionMember functions Static functions Friend functions Access to private membersxxx Is declared in the class scopexx (transparently) Receives this pointerx Vector multiply(const Matrix& m, const Vector& v) { // HOMEWORK } void main() { Matrix m; Vector v(1.0, 2.5, 5.0, 6.0); v = multiply(m, v); }

6Programming IIObject-Oriented Programming Member or Friend? Some operations can be performed only by members: constructor, destructor, virtual functions A function that has to access the members of a class should be a member unless there’s a specific reason for it not to be a member. Member functions must be invoked for objects of their class only; no user defined conversions are applied. Example: class X { public: X(int); void m1(); friend int f1(X&); friend int f2(const X&); friend int f3(X); }; void f() { 7.m1(); // ex1; X(7).m1() is not tried! f1(7); // ex2; f1(X(7)); is not tried because no implicit conversion is used for non-const references f2(7); // ok: f3(X(7)); f3(7); // ok: f3(X(7)); } For example, if transpose function transposes its calling object instead of crating a new transposed matrix then it should be a member of class. Otherwise, prefer member functions because of clearer syntax. More example & discussions when operator overloading is detailed.

7Programming IIObject-Oriented Programming Objects DEFINITION [Object] An object is an instance of a class. It can be uniquely identified by its name, it defines a state which is represented by the values of its attributes at a particular time and it exposes a behaviour defined by the set of functions (methods) that can be applied to it. Objects are created in C++ using variable declaration. If a variable is an instance of a class/struct then it is called object. Syntax: int main(int, char*[]) { Date data; Date oData(25, 12), *today = new Date(15, 03, 2004); cout getDay() getMonth() „/” getYear(); delete today; } X variableName; Example:

8Programming IIObject-Oriented Programming Object Instantiation - Summary No.TypeWhen is constructedWhen is destroyed 1Local variableEach time its declaration is encountered in the execution of the program Each time the program exits the block in which it occurs 2Dynamic allocation (Free-store)Using new operatorUsing delete operator 3Local static variableFirst time its declaration is encountered in the execution of the program Termination of the program 4Array of objectsWhen array is createdWhen array is destroyed 5Non-local objectOnce at the start of programOnce at the termination of the program 6Temporary objectWhen the expression is evaluatedAt the end of the full expression in which it occurs 7Dynamic allocation in user- supplied memory Using an overloaded version of operator new Using delete operator 8Union member 9Non-static member objectWhen the ‘enclosing’ object is createdWhen the ‘enclosing’ object is destroyed

9Programming IIObject-Oriented Programming Local variable int f(int a) { Date d1, d2(03, 03, 2007); // creating the objects if(a>0) { Date d3=d1; // creating object using copy-constructor } // d3 is destroyed Date d4; } // destroying objects REMARKS Example: Objects are destroyed in reverse order of their creation.

10Programming IIObject-Oriented Programming Free store int f(int a) { Date *d1 = new Date(03, 03, 2007); // creating the objects if(a>0) { Date *d2 = new Date; cout << *d2; delete d2; } delete d1; } REMARKS Operator new – allocates and initializes memory from free store for objects Syntax: ―pvar = new type; ―pvar = new type(init-value); ―pvar = new type[size] Operator delete – de-allocates and cleanup memory Syntax: delete pvar; DO NOT FORGET TO DESTROY ALL OBJECTS ALLOCATED USING NEW OPERATOR ! Example:

11Programming IIObject-Oriented Programming Local static variable int f(int a) { static Date d(03, 03, 2007); // static object } // d isn’t destroyed Example: REMARKS The destructors for static objects get called in reverse order when the program terminates.

12Programming IIObject-Oriented Programming Array of objects int f(int a) { Date week[7]; // an array of 7 Date objects Date *year = new Date[365]; delete [] year; } Example: REMARKS A default constructor for Date type is mandatory. There is no way to specify explicit arguments for a constructor in an array declaration. The destructor for each element of an array is invoked when the array is destroyed. Don’t forget the squared brackets in delete to free all the elements

13Programming IIObject-Oriented Programming Non-local variable Date gdate1; int f(int a) { cout << gdate1; } Date gdate2; Non-local = global, namespace or class static variables Example: REMARKS Any global object (declared outside any function) is constructed before main is invoked, in the order of their definitions. The destructors for static objects get called in reverse order when the program terminates. No implementation-independent guarantees are made about the order of construction/destruction of non-local objects in different compilation units (files).

14Programming IIObject-Oriented Programming Temporary object void f(String& s1, String& s2) { // …. cout << s1 + s2; // … } REMARKS Temporary objects are results of expression evaluation (e.g. arithmetic operations) A temporary object can be used as initializer for a const reference or named object. Examples: ―const string& s = s1+s2; ―string s = s1+s2; A temporary object can also be created by explicitly invoke the constructor ―handleComplex(complex(1,2)); Problems may arise. Example: void f(String s1, Strings2) { // … String temp = s1 + s2; cout << temp; delete temp; // … } void f(String& s1, String& s2) { const char* pch = (s1+s2).c_str(); // c_str() returns a C-style, zero-terminated array of chars cout << pch; // pch points to an invalid memory address that was destroyed together with temporary obj. s1+s2 } Example:

15Programming IIObject-Oriented Programming User-supplied memory void* operator new(size_t, void* p) { return p; //zona de def } // Explicit placement operator void* buf = reinterpret_cast (0xF00F); // nasty, nasty! // placement syntax X* p2 = new (buf) X; // invokes operator new(sizeof(X), buf); class PersistentStorage { virtual void* alloc(size_t) = 0; virtual void free(void*)=0; }; void* operator new(size_t s, PersistentStorage* p) { return p->alloc(s); } void destroy(X* p, PersistentStorage* storage) { p->~X(); // explicit call of destructor storage->free(p); // release the memory } PersistentStorage* ps = new FileStorage(“a.bin”); void f() { X* p1 = new (ps) X; X* p2 = new (ps) X[10]; X* p3 = new (ps) X(3); destroy(p1, ps); } Example: REMARKS Should be used with caution! Ask experienced colleagues first.

16Programming IIObject-Oriented Programming Union members class X { }; union AUnion { int x; char name[12]; X obj; // OK: No constructors or destructor defined for type X Date date; // ERROR: Date has constructors and destructor }; REMARKS A union can have member functions. A union can’t have static members. A union can’t have members with constructors or destructor. Example

17Programming IIObject-Oriented Programming Non-static members (I) class Student { Date dob; // non-static member String name; // non-static member public: Student(const char* n, const Date& d); }; Student::Student(const char* n, const Date& d) { dob = d; // 1 name = String(n); // 2 } void f() { Student unStudent(„Popescu”, Date(7, 8, 1978); } Example: REMARKS Steps to initialize dob member: ―Memory allocation ―Initialize it using the default constructor ―Call the assignment operator in line 1 To reduce the steps and enhance the clarity, the constructor for class Student can be re-written as follows: Student::Student(const char* n, const Date& d) : name(n), dob(d) { } Initialization list Steps: ―Memory allocation ―Initialize it using the constructor specified in initialization list (for dob is the copy-constructor)

18Programming IIObject-Oriented Programming Non-static members (II) Order of initialization: 1.Initialize members in order of their declaration in class (the order in initialization list is not important). 2.Call the constructor for the class. Order of destroying: 1.Call the destructor for the class. 2.Call the members’ destructor in reverse order of declaration. Static const integer members can be initialized at its member declaration. The following members can be initialized only using initialization list: ―References (X& member;) ―const (const int member;) ―Types without default constructor (X member;) class Club { Club(); // default constructor is private! public: Club(const char* s); }; class X { static const int ci = 1; // declaration + initialization static const float cf = 9.0; // error: not int! const int i; Date& date; Club club; public: X(int ii, Date& dd, const char* clubName) : i(ii), date(dd), club(clubName) { } }; const int X::ci; // definition

19Programming IIObject-Oriented Programming Class Relationships Association Aggregation Composition Inheritance

20Programming IIObject-Oriented Programming Relationship types Concepts does not exist in isolation. They coexist and interact. Association is a loose relationship in which objects of one class know about objects of the other class ( has-a ) Aggregation is part-whole relationship ( is-part-of ) Composition is similar to aggregation, but is more strict ( contains ) Inheritance is a generalization-specialization relationship ( is-a, kind-of )

21Programming IIObject-Oriented Programming Associations (I) DEFINITION [Association] Association is a loose relationship in which objects of one class know about objects of the other class. Association is identified by the phrase “ has a ”. Association is a static relationship. Read relationships from left to right and from top to bottom Student Course takes Remarks: complicated to maintain => should be avoided as much as possible Implementation: member variables (pointers or references) to the associated object.

22Programming IIObject-Oriented Programming Associations (II) Multiplicity - The multiplicity applies to the adjacent class and is independent of the multiplicity on the other side of the association. StudentCourse takes Reflexive relationships: objects of the same class are related to each other n-ary associations: 0..8 * NotationMeaning 1Exactly one *Zero or many 0..5Zero to five 0..4,6,10Zero to five, six or ten Exactly one (default)

23Programming IIObject-Oriented Programming Aggregation Several definitions exist for aggregation and composition based on the following elements: ― Accessibility: The part objects are only accessible through the whole object. ― Lifetime: The part objects are destroyed when the whole object is destroyed. ― Partitioning: The whole object is completely partitioned by part objects; it does not contain any state of its own. Both agg. and comp. represents a whole-part relationship. DEFINITION [Aggregation] Aggregation is a relationship between part and whole in which: part may be independent of the whole; the relationship between part and whole is long-term; parts may be shared between two containers. Aggregation is identified by the phrase “ is-part-of ”. Aggregation cannot be circular, i.e. an object cannot be part of itself. Example: A car has a color and a radio/mp3 player.

24Programming IIObject-Oriented Programming Composition DEFINITION [Composition] Composition is a relationship between part and whole in which part may not be independent of the whole. Composition is identified by the phrase “ contains ”. The contained object is destroyed once the container object is destroyed => No sharing between objects. Stronger than aggregation. Example: A car contains an engine, four tires, two seats, and one transmission.

25Programming IIObject-Oriented Programming Aggregation vs. Composition [Fowler, 2000, Page 85-87] Differences between aggregation, composition and associations still under debate in software design communities.

26Programming IIObject-Oriented Programming Inheritance DEFINITION [Inheritance] Inheritance is a mechanism which allows a class A to inherit members (data and functions) of a class B. We say “A inherits from B”. Objects of class A thus have access to members of class B without the need to redefine them. Inheritance is identified by the phrase: “ kind-of ” at class level (Circle is a kind-of Shape) “ is-a ” at object level (The object circle1 is-a shape.) B is called superclass, supertype, base class or parent class. A is called subclass, subtype, derived class or child class. Introduced in Simula. Example: Person StudentTeacher Inheritance graph Multiple inheritance: a class has 2 or more parent classes. + name : string + courses : List + university : Organization + Age() : double - getPublications() : List+ Grade(topic) : double

27Programming IIObject-Oriented Programming Further Reading [Pop, 2003] Daniel Pop – C++ Programming Language Lecture Notes [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 11.5, Chapter 10][Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 11.5, Chapter 10] [Sussenbach, 1999] Rick Sussenbach - Object-oriented Analysis & Design (5 Days), DDC Publishing, Inc. ISBN: , 1999 [Chapter 5][Sussenbach, 1999] Rick Sussenbach - Object-oriented Analysis & Design (5 Days), DDC Publishing, Inc. ISBN: , 1999 [Chapter 5] [Mueller, 1996] Peter Müller – Introduction to Object-Oriented Programming Using C++, Globewide Network Academy (GNA) [Section 5.2] [Mueller, 1996] Peter Müller – Introduction to Object-Oriented Programming Using C++, Globewide Network Academy (GNA) [Section 5.2] [Fowler, 2000] Martin Fowler with Kendall Scott – UML Distilled 2 nd Ed, Addison-Wesley, 2000