Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică."— Presentation transcript:

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

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

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

4 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:

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

6 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.

7 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:

8 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

9 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.

10 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:

11 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.

12 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

13 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).

14 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:

15 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.

16 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

17 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)

18 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

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

20 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 )

21 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.

22 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)

23 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.

24 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.

25 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.

26 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

27 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: 1562439820, 1999 [Chapter 5][Sussenbach, 1999] Rick Sussenbach - Object-oriented Analysis & Design (5 Days), DDC Publishing, Inc. ISBN: 1562439820, 1999 [Chapter 5] [Mueller, 1996] Peter Müller – Introduction to Object-Oriented Programming Using C++, Globewide Network Academy (GNA) www.gnacademy.org, 1996 [Section 5.2] [Mueller, 1996] Peter Müller – Introduction to Object-Oriented Programming Using C++, Globewide Network Academy (GNA) www.gnacademy.org, 1996 [Section 5.2] [Fowler, 2000] Martin Fowler with Kendall Scott – UML Distilled 2 nd Ed, Addison-Wesley, 2000


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

Similar presentations


Ads by Google