1 / 28

CLASSES

CLASSES. Moshe Fresko Bar-Ilan University Object Oriented Programing 2007-2008. 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);

idania
Download Presentation

CLASSES

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. CLASSES Moshe Fresko Bar-Ilan University Object Oriented Programing 2007-2008

  2. 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);};

  3. 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) ;}

  4. 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);};

  5. 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 missingDate release1(10,12); // Error: Argument missing

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

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

  8. 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; } // … }

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

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

  11. 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) ; }

  12. 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 ; }

  13. 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; }

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

  15. 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*); }

  16. 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 ;

  17. Constructors and DestructorsWhen 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

  18. Constructors and DestructorsWhen 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

  19. 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 ; }

  20. Constructors and DestructorsWhen 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 ; }

  21. Constructors and DestructorsWhen 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() ; { f() ; } } // what will be the output of the program?

  22. Constructors and DestructorsWhen 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) ; }

  23. Constructors and DestructorsWhen 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?

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

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

  26. 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) { } } ;

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

  28. Exercises • 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. • Define implement and test a set of integers, class Intset. Provide union, intersection, and symmetric differences functions. • Given the program: #include <iostream> int main() { std::cout<<“Hello World\n”; }without changing main() modify it to produce output: Initialize Hello World Clean Up

More Related