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

Slides:



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

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
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ă.
Introduction to Programming Lecture 39. Copy Constructor.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Chapter 7: User-Defined Functions II
Informática II Prof. Dr. Gustavo Patiño MJ
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
CLASSES Moshe Fresko Bar-Ilan University Object Oriented Programing
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Classes: A Deeper Look Systems Programming.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
18. DECLARATIONS.
C++ Review (3) Structs, Classes, Data Abstraction.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2008 Oxford Consulting, Ltd 1 October C++ Classes Enhanced Structures C  struct only permitted to have data members  Functions to.
CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 9 Classes: A Deeper Look, Part I Part II.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 17: Vectors and Arrays 1 Based on slides created by Bjarne Stroustrup.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
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.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
11 Introduction to Object Oriented Programming (Continued) Cats.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Memory as byte array Pointers Arrays relationship to pointers Operator ‘new’ Operator ‘delete’ Copy ctor Assignment operator ‘this’ const pointer Allocating.
Classes II Lecture 7 Course Name: High Level Programming Language Year : 2010.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Learners Support Publications Constructors and Destructors.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Constructor & Destructor
This pointer, Dynamic memory allocation, Constructors and Destructor
CS212: Object Oriented Analysis and Design
Constructors and destructors
Constructors and Destructors
9-10 Classes: A Deeper Look.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Pointers and References
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
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 #5 Agenda Objects Construction and destruction of objects

3Programming 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. The simplest way to create objects in C++ is by variable declaration. If a variable is an instance of a class/struct then it is also called object. Syntax: int main(int, char*[]) { Date day1; Date day2(25, 12), *today = new Date(15, 03, 2004); cout getDay() getMonth() „/” getYear(); delete today; } X variableName; Example:

4Programming 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 the 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

5Programming 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 Example Objects are destroyed in reverse order of their creation.

6Programming IIObject-Oriented Programming Free store (Dynamic allocation) 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; } 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

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

8Programming 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; } 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 Example

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

10Programming IIObject-Oriented Programming Temporary object void f(String& s1, String& s2) { // …. cout << s1 + s2; // … } 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; // destroy 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 class String { char *s; public:

11Programming 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); } Should be used with caution! Ask experienced colleagues first. Example

12Programming 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 void f(); }; A union can have member functions. A union can’t have static members. A union can’t have members with custom constructors or destructor. Example

13Programming 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; name = String(n); } void f() { Date d(7, 8, 1988); Student aStudent(„Popescu”, d); } Steps to initialize aStudent object: (1)Memory allocation = sizeof(Date) + sizeof(String) (2)Call default constructor for Date to initialize dob member (3)Call default constructor for String to initialize name member (4)Call the Student::Student(n,d) constructor (5)Call assignment operator in line dob=d; (6)Call assignment operator in line name=n; Example Remark: the “real” initialization of dob/name objects is done in 2 steps: a default constructor + an assignment operator (steps 2+5 and 3+6)

14Programming IIObject-Oriented Programming Non-static members (II) 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) : name(n), dob(d) { } void f() { Date d(7, 8, 1988); Student aStudent(„Popescu”, d); } To reduce the steps and enhance the clarity, the constructor for class Student can be re- written as follows: Initialization list Steps: (1)Memory allocation = sizeof(Date) + sizeof(String) (2)Call the copy constructor of Date to initialize dob in dob(d) (3)Call the custom constructor of String to initialize name in name(n) (4)Call Student::Student(n,d) Example Remark: the “real” initialization of dob/name objects is done in one step: calling the appropriate constructor

15Programming IIObject-Oriented Programming Non-static members (III) Order of initialization: 1.Initialize members in order of their declaration in class (the order in initialization list is irrelevant). 2.Call the constructor of the class. Order of destroy: 1.Call the destructor of the class. 2.Call the members’ destructor in reverse order of declaration. The following members can be initialized only in initialization list: ―References (X& member;) ―const (const int member;) ―Types without default constructor (X member;) static const integer members (and only these) can be initialized at declaration. 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) { i = ii; // error – const member } }; const int X::ci; // definition

16Programming IIObject-Oriented Programming Further Reading [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 11.5] [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 11.5]