1 / 27

Object Oriented Programming

Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică. Object Oriented Programming. Lect. Dr. Daniel POP. Course #4 Agenda. Classes (continued) Friends. Objects Construction and destruction of objects. Class Relationships Association

mingan
Download Presentation

Object Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. Friends (I) • 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 ;) class Matrix { /* declarations */ } ; class Vector{/* declarations */ }; Define a function that: Vector x Matrix  Vector // 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 } • 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. Object-Oriented Programming

  4. Friends (II) • Friends can be either functions member of another class or global functions. • Syntax: friend ftype fname(arg_list); friend class X; • 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 Object-Oriented Programming

  5. 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&); }; 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);} • 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 => Object-Oriented Programming

  6. 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. Object-Oriented Programming

  7. 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: X variableName; • Example: int main(int, char*[]) { Date data; Date oData(25, 12), *today = new Date(15, 03, 2004); cout << "Astazi este " << azi->getDay() << „/”<< azi->getMonth() „/” << azi->getYear(); delete today; } Object-Oriented Programming

  8. Object Instantiation - Summary Object-Oriented Programming

  9. Local variable • Example: 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 • Objects are destroyed in reverse order of their creation. Object-Oriented Programming

  10. Free store • Example: 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; } DO NOT FORGET TO DESTROY ALL OBJECTS ALLOCATED USING NEW OPERATOR ! • 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; Object-Oriented Programming

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

  12. Array of objects • Example: int f(int a) { Date week[7]; // an array of 7 Date objects Date *year = new Date[365]; delete [] year; } • 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 Object-Oriented Programming

  13. Non-local variable • Non-local = global, namespace or class static variables • Example: Date gdate1; int f(int a) { cout << gdate1; } Date gdate2; • 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). Object-Oriented Programming

  14. Temporary object • Example: void f(String s1, Strings2) { // … String temp = s1 + s2; cout << temp; delete temp; // … } 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, 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 } Object-Oriented Programming

  15. User-supplied memory • Example: 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); destroy(p1, ps); destroy(p1, ps); } void* operator new(size_t, void*p) { return p; //zona de def } // Explicit placement operator void* buf = reinterpret_cast<void*>(0xF00F); // nasty, nasty! // placement syntax X* p2 = new (buf) X; // invokes operator new(sizeof(X), buf); • REMARKS • Should be used with caution! • Ask experienced colleagues first. Object-Oriented Programming

  16. Union members • 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 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 }; Object-Oriented Programming

  17. Non-static members (I) • 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: 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); } 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) Object-Oriented Programming

  18. Non-static members (II) • Order of initialization: • Initialize members in order of their declaration in class (the order in initialization list is not important). • Call the constructor for the class. • Order of destroying: • Call the destructor for the class. • 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 Object-Oriented Programming

  19. Class Relationships • Class Relationships • Association • Aggregation • Composition • Inheritance Object-Oriented Programming

  20. 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) Object-Oriented Programming

  21. Student 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 Course takes • Remarks: complicated to maintain => should be avoided as much as possible • Implementation: member variables (pointers or references) to the associated object. Object-Oriented Programming

  22. Associations (II) • Multiplicity - The multiplicity applies to the adjacent class and is independent of the multiplicity on the other side of the association. Student Course takes 0..8 * • Reflexive relationships: objects of the same class are related to each other • n-ary associations: Object-Oriented Programming

  23. 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. Object-Oriented Programming

  24. 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 . Object-Oriented Programming

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

  26. 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 + name : string + Age() : double • Inheritance graph • Multiple inheritance: a class has 2 or more parent classes. Student Teacher + university : Organization + courses : List<Course> + Grade(topic) : double - getPublications() : List Object-Oriented Programming

  27. 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] • [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] • [Fowler, 2000] Martin Fowler with Kendall Scott – UML Distilled 2nd Ed, Addison-Wesley, 2000 Object-Oriented Programming

More Related