Download presentation
Presentation is loading. Please wait.
Published byHenry Lynch Modified over 8 years ago
1
SNU OOPSLA Lab. 10. Classes © copyright 2001 SNU OOPSLA Lab.
2
SNU OOPSLA Lab. C++ 2 Contents Concepts and classes Class members and Access control Constructors Static members Default copy Const member functions This Structure & Union In-class function definition Concrete class member functions and helper functions
3
SNU OOPSLA Lab. C++ 3 Contents Overloaded operators Use of concrete classes Destructors Default construction Local variables User-defined copy New and Delete Member objects Arrays Static Storage Temporary variables
4
SNU OOPSLA Lab. C++ 4 1~2 Concepts and classes Class : a tool for creating new types like as built-in types Well chosen class easier to understand easier to modify makes a program more concise makes many sorts of code analysis feasible enables the compiler to detect illegal uses of objects
5
SNU OOPSLA Lab. C++ 5 2.1~2.2 Class member and access control Class Date { int d,m,y; public : void int(int dd,int mm, int yy);//initialize void add_year(int n);//add n years void add_month(int n);//add n months void add_year(int n);//add n days }; void Date::init(int dd,int mm,int yy) {d=dd; m=mm;y=yy; }
6
SNU OOPSLA Lab. C++ 6 Inlinevoid Date::add_year(int n) { y+=n; } void timewarp(Date &d) { d.y-=200;//error : Date::y is private }; 2.1~2.2 Class member and access control
7
SNU OOPSLA Lab. C++ 7 m y d init() add_year() add_month() date private part public part add_year() 2.1~2.2 Class member and access control
8
SNU OOPSLA Lab. C++ 8 2.3 Constructors A constructor allows the programmer to declare a functionwith the explicit purposes of initializing object.
9
SNU OOPSLA Lab. C++ 9 2.3 Constructors Use constructor instead of init() class Date{ int d,m,y; public : //… Date(int,int,int);//day,month,year Date(int,int);//day,month,today’s year Date(int);//day,today’s month and year Date();//default Date: today Date(const char*)//date in string representation }; Date today(4); Date july4(“July 4,1983”); Date guy(“5 Nov”); Date now;//default initialized as today
10
SNU OOPSLA Lab. C++ 10 2.3 Constructors Class Date { int d,m,y; public: Date(int dd=0,int mm=0,int yy=0); //… }; Date::Date(ini dd,int mm,int yy) { d = dd? dd: today.day; m=mm? mm: today.month; y=yy? yy: today.year; }
11
SNU OOPSLA Lab. C++ 11 2.4 Static Members A static data member is shared by all objects of the class in a program. Static member function A function that needs access to members of a class, yet doesn’t need to be invoked for a particular object class Date { int d, m,y; static Date default_date; public: Date(int dd=0;int mm=0;int yy=0); //… static void set_default(int, int, int); };
12
SNU OOPSLA Lab. C++ 12 2.4 Static Members Static members can be referenced with the name of its class instead of mentioning an object void f() { Date::set_default(4,5,1945); }
13
SNU OOPSLA Lab. C++ 13 2.4 Static Members Date Date::default_date(16,12,1770); void Date::set_default(int m,int d,int y) { Date::default_date = Date(m,d,y); } Date copy_of_default_date = Date(); Static members of a class must be defined somewhere
14
SNU OOPSLA Lab. C++ 14 default_date set_default Date a Date b Date c default_date set_default default_date set_default default_date set_default 2.4 Static Members
15
SNU OOPSLA Lab. C++ 15 2.5 Default copy Date d = today; void f(Date & d) { d = today; } When initialized with a copy of another object of same class Default copy is memberwise copy
16
SNU OOPSLA Lab. C++ 16 2.6 Const member functions The const indicates that the following functions do not modify the static of members Class Date { int d,m,y; public: int day() const {return d;} int month() const {return m;} int year() const ; //… }; inline int Date::year() const { return m++; //error: attempt to change member value in const function }
17
SNU OOPSLA Lab. C++ 17 2.6 Const member functions The const suffix is required outside its class Inline int Date::year() const//correct {return y; } inline int Date::year() //error: const missing in member function type {return y; } void f(Date &d,const Date&cd) {int j= cd.year();//ok cd.add_year(1); //error: cannot change value of const cd }
18
SNU OOPSLA Lab. C++ 18 2.7 Self-Reference This points to the object for which a member function is invoked.
19
SNU OOPSLA Lab. C++ 19 class Date{ //… Date &add_year(int n);//add n years Date &add_month(int n);//add n months Date &add_day(int n);//add n days }; Date &Date::add_year(int n) { if(this->d==29 && this->m==2 && !leapyear(this->y+n)){ this->d=1; this->m=3; } this->y +=n; return *this; } 2.7 Self-Reference
20
SNU OOPSLA Lab. C++ 20 2.7.1 Self-Reference -physical and logical constness Logical constness Some detail that the user cannot directly observe is updated
21
SNU OOPSLA Lab. C++ 21 Class Date{ bool cache_valid; string cache; valid compute_cache_rep() const ; public: //... String string_rep() const; // string representation }; String Date::string_rep() const { if (cache_valid == false){ Date *th=const_cast (this);//cast_away const th->compute_cache_value(); th->cache_valid=true; } return cache; } 2.7.1 Self-Reference -physical and logical constness
22
SNU OOPSLA Lab. C++ 22 Class Date { mutable bool cache_valid; mutable string cache; void compute_cache_value(); public: string string_rep() const;//string representation }; string Date::string_rep() const { if (!cache_valid){compute_cache_value(); cache_valid = true; }return cache; } 2.7.2 Self-Reference -mutable Declaring the data in the cache to be mutable The explicit type conversion and its consequent implementation-dependent behavior can be avoided
23
SNU OOPSLA Lab. C++ 23 2.8 Struct and Union A struct is simply a class where members are public by default. A union is a struct where every member has the same address.
24
SNU OOPSLA Lab. C++ 24 Struct s{ … Class s {public:... 2.8 Struct and Union
25
SNU OOPSLA Lab. C++ 25 2.9 In-Class Function -Definitions A member function defined in the class declaration is taken to be inline. A member function can also be declared inline outside the class declaration.
26
SNU OOPSLA Lab. C++ 26 2.9 In-Class Function - Definitions class Date { //perfect but potentially confusing public: int date() const {return d;} //… } class Date { public:int day() const //… } inline int Date::day() const {return d;}
27
SNU OOPSLA Lab. C++ 27 3. Concrete Class The designer of a general-purpose PL cannot foresee the detailed needs, so mechanisms must be provided for the user to define small concrete types
28
SNU OOPSLA Lab. C++ 28 A better date class 3. Concrete Class Class Date { public: enum Month{jan=1,feb,mar,apr…..,dec}; class Bad_Date{};//exception class Date(int d=0,Month m=Month(0),int y=0);//0 means “pick a default” int day() const; Month month() const;int year() const; // for examing the Date string string_rep() const;//string representation void char_rep(char s[]) const; //C-style string representation static void set_default(int,Month,int); Date& add_year(int n); Date& add_month(int n);Date& add_day(int n); //for changing the Date private: int d, m,y;//representation static Date default_date; }; These operations is typical for a user-defined type : constructor functions for examining a Date functions for manipulating Dates operations to allow Dates to be freely copied a class for reporting errors as exceptions
29
SNU OOPSLA Lab. C++ 29 Constructor checks the data validation and other member functions can rely on it and must maintain it => This can simplify code Separation function for data validation => This made code more complicated and less robust than the exception 3.1~3.2 Member functions & Helper functions
30
SNU OOPSLA Lab. C++ 30 3.1~3.2 Member functions & Helper functions Date::Date(int dd,Month mm, int yy) {if (yy==0)… if (mm==0)… if (dd==0)… switch(mm) { case feb:… case apr:case jun:case sep:case nov:… case jan:case mar:case may:case jul:case aug:case oct::case dec:…. default: throw Bad_date(); } if(d<1||max <<d) throw Bad_date(); y=yy; m=mm; d=dd; }
31
SNU OOPSLA Lab. C++ 31 Functions in a class not to access to the representation made the class interface complicated and the number of functions increased How are such functions “associated” with class Date? Their declarations were simply placed in the same file as the declaration of class Date 3.1~3.2 Member functions & Helper functions Int diff(Date a, Date b); bool leapyear(int y); Date next_weekday(Date d); #include “Date.h”
32
SNU OOPSLA Lab. C++ 32 3.3 Overloaded Operators Add functions to enable conventional notation Inline bool operator==(Date a,Date b)//equality {return a.day()==b.day() && a.month()==b.month() && a.year()==b.year(); } bool operator!=(Date, Date);//inequality; bool operator<(Date, Date);//less than bool operator>(Date,Date);//greater than
33
SNU OOPSLA Lab. C++ 33 3.4 Use of concrete classes The intent of a concrete type To do a single, relatively small thing well and efficiently Not to provide the user with facilities to modify Not to display polymorphic behavior
34
SNU OOPSLA Lab. C++ 34 4.1 Destructors A destructor ensure proper clean-up and release of resources A destructor is called whenever an object of that class is destroyed A destructor must be called for each element of an array when that array is destroyed. --> use delete[]
35
SNU OOPSLA Lab. C++ 35 4.1 Destructors class Name { const char*s; //… }; class Table{ Name *p; size_t sz; public: Table(size_t s=15){p=new Name[sz=s];}//constructor ~Table(){delete[] p;}//destructor }
36
SNU OOPSLA Lab. C++ 36 4.2 Default Constructors A default constructor is a constructor that can be called without supplying an argument
37
SNU OOPSLA Lab. C++ 37 4.2 Default Constructors Table tt;//call default constructor, Table(15) struct X { const int a; const int &r; }; X x;//error: no default constructor for X
38
SNU OOPSLA Lab. C++ 38 4.4 Local variables The constructor for a local variable is executed each time the thread of control passes through the declaration of the local variable void f(int i) {Table aa; Table bb; if (i > 0){ Table cc; } Table dd; }
39
SNU OOPSLA Lab. C++ 39 4.4.1 User-defined Copy Memberwise copy is usually the wrong semantics for copying objects containing resources managed by a constructor/destructor pair A copy constructor initializes uninitialized memory, whereas the copy assignment operator must correctly deal with a well-constructed object
40
SNU OOPSLA Lab. C++ 40 void h() {Table t1; Table t2=t1;//copy initialization: troubleTable t3; t3 = t2;//copy assignment: trouble } class Table{ Table(const Table&);//copy constructor Table &operator=(const Table&);//copy assignment }; 4.4.1 User-defined Copy
41
SNU OOPSLA Lab. C++ 41 Table::Table(const Table &t)//copy constructor {p=new Name[sz=t.sz]; for (int I=0;I<sz;I++) p[I]=t.p[I]; } Table &Table::operoator=(const Table& t)//assignment {if (this != &t) {//beware of self-assignment: t=t delete[] p; p= new Name[sz=t.sz]; for(int I=0;I<sz;I++)p[I]=t.p[I]; } return *this; } 4.4.1 User-defined Copy
42
SNU OOPSLA Lab. C++ 42 4.5 New and Delete An object on the free store has its constructor by the new operator and disappear by the delete operator int main() { Table * p = new Table; Table *q = new Table; delete p; delete p;// probably causes run-time error }
43
SNU OOPSLA Lab. C++ 43 4.6 Member Objects Member initializer class_name ::member(arguments):,,, ; Construction order in a constructor Order of declaration in the class rather than in the initalizer list Destruction order Body of its own destructor and then members’ destructor Club::Club(const string &n,Date fd) :name(n),members(),officers(),founded(fd){ } is equal to Club::Club (const string &n, Date fd) :name(n),foundedd(fd) {}
44
SNU OOPSLA Lab. C++ 44 4.6 Member Objects name is initialized with a copy of n address is first initialized to the empty string and a copy of a is assigned Class Person { string name; string address; Person(const string &n,const string & a); … } Person::Person(const string n, const string& a) :name(n) {address = a; }
45
SNU OOPSLA Lab. C++ 45 4.6 Member Objects A constant-expression initializer to its member declaration Initialize a static integral constant member Class Curious { static const int c1 = 7; //ok,but remember definition static int c2 = 11;//error: not const const int c3=13;//error: not static static const int c4 = f(17);//error: in-class initializer not const static const float c5 = 7.0//error:in-class not integral }
46
SNU OOPSLA Lab. C++ 46 4.6 Member Objects Copying Members A default constructor or default copy assignment copies all elements of a class Class Unique_handle{ private://copy operations are private to prevent copyng Unique_handle(const Unique_handle&); Unique_handle& operator=(const Unique_handle&); public://… }; struct Y{Unique_handle a;//require explicit initialization }; Y y1;//error: cannot copy Y::a Y y2= y1;
47
SNU OOPSLA Lab. C++ 47 4.7 Array If you absolutely must initialize members of an array with different values, you can write a default constructor that directly or indirectly read and writes nonlocal data Class lbuffer{ string buf; public: lbuffer() { cin>>buf; } }; void f() { lbuffer words[100];//each word initialized from cin }
48
SNU OOPSLA Lab. C++ 48 4.7 Array void f(int sz) { Table *t1 = new Table; Table *t2 = new Table[sz]; Table *t3 = new Table; Table *t4 = new Table[sz]; delete t1;//right delete[] t2;//right delete[] t3;//wrong: trouble delete t4;//wrong: trouble } The programmer must state whether an array or an individual object is being deleted
49
SNU OOPSLA Lab. C++ 49 4.7 Array Can use a class such as vector instead of array void g() {vector *p1 = new vector (10); Table* p2=new Table; delete p1; delete p2; }
50
SNU OOPSLA Lab. C++ 50 4.8 Static Storage The constructor for a local static object is called the first time the thread of control passes through the object’s definition The destructors for local static objects are invoked when the program terminates void f (int i) {static Table tbl; //… if (i){static Table tbl2; } int main() {f(0); f(1); f(2); }
51
SNU OOPSLA Lab. C++ 51 4.9 Static Storage A variable(nonlocal store) defined outside any function is initialized before main() is invoked The order of construction : tbl, X::memtbl, Z::tbl2 ( in order their definitions occur, not declaration) Class X {static Table memtbl; }; Table tbl; Table X::memtbl; namespace Z{ Table tbl2; }
52
SNU OOPSLA Lab. C++ 52 4.9 Static Storage A first-time switch Class Zlib{ static bool initialized; static void initialize() { /*initialize */ initialized = true;} public: //no constructor void f() {if (initialized==false) initialize(); } };
53
SNU OOPSLA Lab. C++ 53 4.10 Temporary Variables A temporary object is destroyed at the end of the full expression in which it was created void f(string &s1, string &s2, string &s3)//obscure problem {const char* cs =(s1+s2).c_str(); cout<<cs; if (strlen(cs=s2+s3).c_str())<8&&cs[0]==‘a’){ //cs used here } A temporary object holding s1+s2 is deleted at the end of the expression. cs points to deallocated storage The condition will work well. However the temporary is destroyed before the controlled statement is entered
54
SNU OOPSLA Lab. C++ 54 4.10 Temporary Variables modified example A temporary can be used as an initializer for a const reference void f(string& s1,string& s2, string &s3) {cout<<s1+s2; string s=s2+s3; if (s.length()<7 && s[0]==‘a’) { //use s here} } void g (const string &); void h(string& s1,string &s2) {const string& s=s1+s2; //use s here g(s); }
55
SNU OOPSLA Lab. C++ 55 4.11 Temporary Variables Placement of objects : supplying extra arguments when using new void * operator new(size_t,void *p){ return p;} //explicit placement operator void* buf=reinterpret_cast (0xF00F); //significant address X* p2= new (buf)X; //construct an X at ‘buf:’ invokes :operator new(sizeof(X).buf)
56
SNU OOPSLA Lab. C++ 56 Class Arena { public: virtual void* alloc(size_t)=0; virtual void free(void*) = 0; }; void *operator new(size_t sz,Arena* a) { return a->alloc(sz);} extern Arena* Persistent; extern Arena* Shared; void g(int I) {X* p=new (Persistent) X(I);//X in persistent storage X* q=new (Shared) X(I);//X inshared memory } void destroy(X *p,Arena *a) {p->~X();//call destructor a->free(p);//free memory } SNU OOPSLA Lab.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.