CLASSES Moshe Fresko Bar-Ilan University Object Oriented Programing 2007-2008.

Slides:



Advertisements
Similar presentations
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Advertisements

C++ Classes & Data Abstraction
Informática II Prof. Dr. Gustavo Patiño MJ
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
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];
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Pointers and Dynamic Objects Mechanisms for developing flexible list representations.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
CS-2303 System Programming Concepts
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.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Pointer Data Type and Pointer Variables
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
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.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Basic Concepts of OOP in C++ Darvay Zsolt. C++ 2 Outline  The namespace and its members  The using declaration and directive  The address operator.
C++ Review (3) Structs, Classes, Data Abstraction.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
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.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
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.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Constructors & Destructors, Proxy Classes, Friend Function and example of static member.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Classes struct Public and Private Parts of a struct Class Scope of a Class Overloading Member Functions Class in a Class Static Members of Classes this.
Advanced Programming Constants, Declarations, and Definitions Derived Data Types.
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.
SNU OOPSLA Lab. 10. Classes © copyright 2001 SNU OOPSLA Lab.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Classes with Dynamically Allocated Data
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Classes Short Review of Topics already covered Constructor
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
C++ Constructor Insanity CSE 333 Summer 2018
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

CLASSES Moshe Fresko Bar-Ilan University Object Oriented Programing

Class A class is a user defined type. C example struct Date { int d, m, y ; }; void initDate (Date* d, int day, int month, int year); void addYear (Date* d, int n); void addMonth (Date* d, int n); void addDay (Date* d, int n); C++ example struct Date { int d, m, y ; void init (int day, int month, int year); void addYear (int n); void addMonth (int n); void addDay (int n); };

Classes Definition of member functions void Date::init(int day, int month, int year) { d = day; m=month; y=year; } void Date::addYear(int n) { y+=n; } Usage Date myBirthDay ; void f() { Date today ; today.init(24,10,2005) ; myBirthDay.init(19,5,1919) ; Date tomorrow = today ; tomorrow.addDay(1) ; }

Access Control Access Control Modifiers public: Accessible from every place private: Accessible only within the class protected: Accessible within the current class and subclasses Default Control Modifiers struct => public class => private Example class Date { int d, m, y ; public: void init (int day, int month, int year); void addYear (int n); void addMonth (int n); void addDay (int n); };

Constructors A constructor is called whenever an object is created. It has the same name as the class. Example: class Date { Date (int, int, int) ;// Constructor } … Date today=Date(26,10,2005); Date sukot(18,10,2005); Date myBirthday;// Error: Initialization missing Date release1(10,12);// Error: Argument missing

Constructor Providing several Constructors class Date { int d, m, y; public: // … Date ( int, int, int ); Date ( int, int );// day, month, today ’ s year Date ( int );// day, today ’ s month and year Date ( );// default date is today Date (const char*);// from string representation } … Date today(27); Date july4( “ July 4, 1983 ” ); Date now;

Static Members A variable that is part of a class, but is not part of an object, is called a static member. There is exactly one copy of the static member. Example: class Date { int d, m, y; static Date default ; public: Date ( int dd=0,int mm=0, int yy=0); // … static void set_default ( int, int, int) ; }

Copying Class Objects By default, the copy of a class object is a copy of each member. Date d = today ; The change this behavior a copy constructor can be provided in the form X::X(const X&) class Date { Date(const Date&x) { d=x.d; m=x.m; y=x.y; } // … }

Constant member functions const modifier after function declaration indicates that the function does not modify the state. class Date { int d,m,y; public: int getDay() const { return d ; } int getYear() const ; // … } // inline int Date::getYear() const //{ return y++; } // Error // inline int Date::getYear()// Error //{ return y; } inline int Date::getYear() const { return y; }

Constant member functions Non-const objects both const and non-const member functions can be invoked. For const objects only const member functions can be invoked. void f(Date& d, const Date& cd) { int i = d.getYear() ; // ok d.addYear(1) ; // ok int j = cd.getYear() ; // ok cd.addYear(1) ;// Error

Self-reference For update functions it is often useful to return self-reference by using *this reference. ( this: a pointer to the object in which a member function is invoked). class Date { Date& addYear(int i) ; Date& addMonth(int i) ; Date& addDay(int i) ; // … } Date& addYear(int i) { y+=n ; return *this ; } // … void f(Date& date) { date.addYear(1).addMonth(1).addYear(1) ; }

Mutable variables The storage modifier mutable specifies that a member should be stored in a way that allows updating even when it is a member of a const object. class Date { mutable string cache ; // … public: // … string toString() const ; } string Date::toString() const { if (cache.empty()) cache = computeStringRepresentation() ; return cache ; }

In-class Function Definitions A member function defined within the class definition is taken to be an inline member function. class Date { // … public: int day() const { return d; } } // Alternatively class Date { // … public: int day() const ; } inline int Date::day() const { return d; }

Constructors and Destructors Constructor A constructor initializes an object. It is called when the object is first created. It is a function with the same name of the class. If none is defined then default constructor used otherwise there is no automatic default constructor. Destructor A destructor is called when an object is destroyed. It typically does clean-up and resource release. It is called when an automatic variable goes out of scope or an object on the free store is deleted. It is a function with the same name of the class only with a ~(Tilda) in the beginning.

Constructors and Destructors Default Constructor: It is the constructor that is called without supplying any argument. class Name { const char* s; // … } class Table { Name* p ; int size ; public: Table (int s=15) { p = new Name[size=s] ; } ~Table() { delete[] p ; } Name* lookup(const char*) ; bool insert(Name*); }

Constructors and Destructors If the user didn ’ t define any constructor the compiler will create one which is a default constructor automatically. class A { private: int val ; public: A() { val=0; } } class B { private: int val ; public: B(int i) { val=i; } } class C { private: int val ; } // which of these definitions will give compiler error ? A a ;B b ;C c ; A* ap ;B* bp ;C* cp ;

Constructors and Destructors When they are called? 1. A named automatic object is created each time its declaration is encountered and destroyed when the program exits the block in which it occurs. class A { private: int num ; public: int getNumber() const { return num ; } public: A(int i=0) { num=i; cout<<i<< “ ctor ” <<endl; public: ~A() { cout<<i<< “ dtor ” <<endl; } } int main() { A x(1) ; { { A y(2) ; } A z(3) ; } // What will be the output of the program

Constructors and Destructors When they are called? 2. A free-store object is created when the new operator is called and destroyed when the delete operator is called. int main() { A* ap1=new A(1) ; A* ap2=null; { ap2=new A(2) ; A* ap3 = new A(3) ; } delete ap1 ; delete ap2 ; } // what will be the program output

Constructors and Destructors When they are called? 3. A non-static member object inside another class is created when this class ’ instance is created and destroyed when this instance is destroyed. class B { private: A a ; public: B(int i=3) : a(i) { } } int main() { B b1(1) ; { B b2(2) ; } B b3 ; }

Constructors and Destructors When they are called? 4. An array element is created and destroyed when the array elements are created and destroyed. void main() { cout << “ 1 ” << endl ; A aarr[3] ; cout << “ 2 ” << endl ; { cout << “ 3 ” << endl ; A aarr[4] ; cout << “ 4 ” << endl ; } cout << “ 5 ” << endl ; }

Constructors and Destructors When they are called? 5. A local static object is created the first time its declaration is encountered, and destroyed at the termination of the program. int f() { static A a(3) ; // other things } int main() { A a(1) ; f() ; { f() ; } } // what will be the output of the program?

Constructors and Destructors When they are called? 6. A global, namespace or class static object is created at the start of the program, and destroyed at the end. A a(1) ; class D { static A a ;// we need definition in C++ as: // A D::a() ; } ; int main() { A a(2) ; }

Constructors and Destructors When they are called? 7. A temporary object that is created as part of the evaluation of an expression and destroyed at the end of the full expression it occurs. A sum(const A& a1, const A& a2) { return A(a1.getNumber()+a2.getNumber()) ; } int main() { A a1(1) ; A a2(2) ; int i = sum(a1,a2).getNumber() ; } // What will be the output of the program?

Copying objects By default copying objects means copying of each non-static member variables. Most of the time it is ok. But sometimes it can cause problems. Especially when we have locally managed pointers to objects (on heap) or open external resources (files), etc. Example: The Table example will have problems. void h() { Table t1 ; Table t2 = t1 ; // Copy Initialization. Problem. Table t3 ; t3 = t2 ;// Copy Assignment. Problem.

Copying Objects Solution: To define the Copy constructor and operator equals(=). class Table { // … public: Table( const Table& ) ; Table& operator=(const Table& ) ; } Table::Table ( const Table& t) { p = new Names[size=t.size] ; for (int i=0;i<size;++i) p[i]=t.p[i] ; } Table& Table::operator=(const Table& t) { if (this!=&t) { delete[]p ; p = new Names[size=t.size] ; for (int i=0;i<size;++i) p[i]=t.p[i] ; } return *this ; }

Member initialization class Club { string name ; Table members ; Table officers ; Date founded ; // … Club (const string& n, Date fd) ; Club::Club( const string& n, Date fd) : name(n), members(), officers(), founded(fd) { /* other initializations */ } } ; class X { const int i ;// no other way to initialize, only member initialization Club c ; Club& pc ;// no other way to initialize X(int ii, const string& n, Date d, Club& c) : i(ii), c(n,d), pc(c) { } } ;

Advices 1. Represent concepts as classes 2. Use struct when it really is just data 3. Make a member function const, if it doesn ’ t modify anything. 4. If a constructor acquires a resources, it needs a destructor to return it. 5. If a class has a pointer, then it probably needs a copy constructor and assignment operation. 6. Check for self assignment for copy assignment.

Exercises 1. Define a class Histogram that gets in the constructor two values representing the intervals. Then keeps counts of numbers in that interval. Provide functions to print out the histogram. Handle out of range values. 2. Define implement and test a set of integers, class Intset. Provide union, intersection, and symmetric differences functions. 3. Given the program: #include int main() { std::cout<< “ Hello World\n ” ; } without changing main() modify it to produce output: Initialize Hello World Clean Up