Chapter 3 Classes - PowerPoint PPT Presentation

1 / 79
About This Presentation
Title:

Chapter 3 Classes

Description:

Chapter 3 Classes – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 80
Provided by: ccNct
Category:
Tags: chapter | classes | dane | great

less

Transcript and Presenter's Notes

Title: Chapter 3 Classes


1
Chapter 3Classes
  • Richard JohnsonBaugh
  • Martin Kalin
  • Reporterwangwei

2
Outline
  • 3.1 Classes and Objects
  • 3.2 Sample ApplicationA Stack Class
  • 3.3 Efficiency and Robustness Issues for classes
    and objects
  • 3.4 Sample Application A Time Stamp Class
  • 3.5 Constructors and the Destructor
  • 3.6 Sample ApplicationA Task Class
  • 3.7 Class Data Members and Methods
  • 3.8 Pointers to Objects Common Programming Errors

3
3.1Classes And Objects
  • Class Declarations
  • Information Hiding in C
  • The Member Selector Operator
  • Class Scope
  • The difference between the Keywords class and
    struct
  • Defining Class Methods
  • Using Classes in a Program

4
Class declaration
  • Classes Declarations
  • In C, A class is a data type
  • A Class declaration creates a class as a data type

5
Example 3.1.1 The class declaration
Class Human // data member and methods go
here
1.Creates the class human 2.Describes the data
members and methods that characterize a Human
6
Class declaration
  • The term class is a keyword
  • The term Human is sometimes called the class tag
  • Tag is the identifier or name of the data type

7
Create an Object
  • Human maryLeakey//create an object
  • Defines a variable maryLeakey of type Human
  • Int x
  • A variable of a class data type is an object

8
Class and Object
  • A class declaration must come before the
    definition of any class objects
  • Human maryLeakey//usual style
  • Class Human fred//legal but unusual style
  • We can define either stand-alone objects or
    arrays of objects
  • Human latvians3600000

9
Extend the C structure
  • The C class extends the C structure
  • The keyword struct,used in C,creates a class
  • Example 3.1.3
  • struct Human
  • //.data members and methods go //here

10
Information Hiding in C
  • Privatebe used to hide class data members and
    methods
  • Publicbe used to expose data members and methods
  • Protected see chapter 4
  • In oop
  • Privateimplementation
  • Publicinterface

11
Example 3.1.4
Class person Public void setAge(unsigned
n) unsigned getAge() const Private unsigned
age
12
The Member Selector Operator
  • Access to any class member
  • Member selector operator .
  • Class indirection operator -

13
Example 3.1.5
Class person Public void setAge(unsigned
n) unsigned getAge() const Private unsigned
age Int main() person boxer boxer.setAge(
27) //remainder of mains body
14
Example 3.1.6
include Using namespace std Class
person Public void setAge(unsigned
n) unsigned getAge() const Private unsigned
age Int main() person boxer Boxer.setAge(
27) cout private
15
Class Scope
  • A classs private members have class scope
  • Private members can be accessed only by class
    methods
  • In C, members default to private if the
    keywords public or protected are not used
  • One style is to put the public members first
    inside a declaration

16
Example 3.1.7
Class c Public void m()//public
scope Private char d //class scope(private
scope)
Class z Int x
17
The difference between the Keywords class and
struct
  • Class
  • All members default to private
  • Struct
  • All members default to public

18
Example
Class c int x void m()
Struct c int x void m()
19
Defining Class Methods
  • Class methods may be defined in two ways
  • A method may be declared inside the class
    declaration but defined outside the class
    declaration
  • A method may be defined inside the class
    declaration, called inline

20
Example 3.1.11 3.1.12
Class person Public void setage(unsigned
n) agen unsigned getage () const
return age Private unsigned
age
Class person Public void setage(unsigned
n) unsigned getage () const Private unsigned
age // define persons setage Void
personsetage (unsigned n) agen //
define persons getage Unsigned persongetage()
const return age
21
Using Classes in a Program
  • 1. the class declarations
  • 2. Object definitions
  • 3. Client requests for services

22
A complete program using a class
include Using namespace std Class
person Public void setage(unsigned n) age
n unsigned getage () const return age
Private unsigned age Int main ()
person p // create a single person person
stooges 3 //create an array of
persons p.setage (12) // set ps name // set
the stooges ages stooges0..setage(45) stooge
s1. Setage(46) stooges2. Setage(44) //
print four ages cout (int I 0 I stoogesI.getage() 23
3.2 Sample ApplicationA Stack Class
  • Problem
  • Create a Stack class that supports pushes and
    pops of ints

24
Sample Output
  • Figure 3.2.1

25
C Implementation
  • See Page 110111

26
Discussion
  • Stack class encapsulates six high-level,public
    methods that constitute its inter face
  • Init
  • Push
  • Pop
  • isFull
  • isEmpty
  • dump

27
3.3 Efficiency and Robustness Issues for classes
and objects
  • Passing and Returning Objects by Reference
  • Object References as const Parameters
  • Const Methods
  • Overloading Methods to Handle Two Types of
    Strings

28
The First
  • Classes and Objects make up the core of OOP
  • They are powerful but potentially inefficient
  • To Introduce ways in efficient ways

29
Passing and Returning Objects by Reference
  • Objects,like other variables, may be passed by
    reference to functions
  • There are three reasons
  • The object passed or return by value must be
    copied
  • The copying itself takes time
  • By reference is easier then passing and returning
    a pointers to objects at the syntax level

30
Example 3.3.1
  • The program illustrates passing and returning
    objects by reference
  • Object c1 is passed from main to function f
  • Function g returns the local static object c3
  • IF c3 were auto, then g would return to its
    invoker a reference to a nonexistent object

31
include using namespace std class
C public void set(int n)numn int
get()const return num private int
num void f(c) c g()
32
int main() C c1,c2 f(c1)//pass by
reference c2g()//return by reference coutget()c) c.set(-999) coutg() static C c3//NBstatic, not
auto c3.set(123) return c3
33
Object References as const Parameters
class C public void setName(const string
n) namen //.other public members private st
ring name
34
Cont.
  • Method setNames string parameter n is marked as
    const
  • To signal that setname does not change n but
    only assigns n to the data member
  • If an object is passed by reference to a function
    that does not change the objects state
  • the Functions parameter should be const

35
Const Methods
  • If the method does not change an objects data
    members
  • Directly
  • Indirectly
  • Invoking other methods that changes the objects
    state

36
Example 3.3.2
class C public void set(int n)numn int
get()const return num private int num
37
Cont.
  • get is marked as const
  • get does not change the value of any c data
    member
  • The const occurs between the methods argument
    list and its body
  • get is a read-only method
  • set cannot be marked const

38
Example 3.3.3 class c
class C public void m1( int x)
const m2(x)//error m2 not
const void m2( int x)dmx private int
dm
39
Example 3.3.4 the class
class C public void set (const string
n)namen const string get() const return
name private string name
40
Cont. 3.3.4
  • Three const
  • In method set,parameter
  • Const method get()
  • Return a const reference

41
Overloading Methods to Handle Two Types of
Strings
class C public void set(const string
n)namen void set(const char
n)namen const string get()const return
name private string name
42
3.4 Sample Application A Time Stamp class
  • Problem
  • A time stamp is a value that represent an instant
    in time
  • Can be used to record when an event occurs
  • TimeStamp class
  • Set a time
  • Print a time as an integer
  • Print a time as a string
  • Decompose a time

43
3.5 Constructors And The Destructor
  • Constructors
  • Arrays of Class Objects and the Default
    Constructor
  • Restricting Object Creation Through Constructors
  • The Copy Constructor
  • Defining a Copy Constructor

44
3.5 Constructors And The Destructor
  • Disabling Passing and Returning by Value for
    class Objects
  • Convert Constructors
  • The Convert Constructor and Implicit Type
    Conversion
  • Constructor Initializers
  • Constructors and the Operators new and new
  • The Destructor

45
The First
int main() window mainWin mainwin.show()
  • Class methods typically are invoked by name
  • Some methods need not be invoked explicitly by
    name
  • Class constructors and the class destructor are
    invoked automatically by the compiler

46
Constructors
  • A constructor is a method whose name is the same
    as the class name
  • A suitable constructor is invoked automatically
    whenever an instance of the class is created

47
Example 3.5.2
class Person public person()
//constructor person(const string n)
//constructor person(const char
n)//constructor void setName(const string
n) void setName(const char n) const string
getName()const private string name
48
Constructors
  • A constructor must not have a return type
  • Class constructors can be overload
  • Each constructors must have a distinct signature
  • Default constructorcan be invoked with no
    arguments
  • Parameterized constructors--other constructors

49
Example 3.5.3
include person.h int main() person
anonymous //Default constructor person
jc(J.Coltrne)// parameterized
constructor //
50
Constructors
  • A constructor is a method called when an object
    is first constructed
  • Constructor are used to initialize data members
    and to do any other processing appropriate to an
    objects creation
  • A constructor can do anything that other function
    do
  • Constructors may be defined inside or outside

51
Example 3.5.4
include stack.h int main() stack
s1 s1.push(89)//Trouble top not initialized
class Stack stack()init()//ensures
initialization
52
Example 3.5.5
class Person public person()nameUnknown
person(const string n) person(const char
n) void setName(const string n) void
setName(const char n) const string
getName()const private string name
personperson(const string n) namen
53
Arrays of Class Objects and the Default
Constructor
  • If C is a class,we can define arrays of c
  • If c has a default constructor, the default
    constructor is invoked for each c object in the
    array

54
Example 3.5.6
include using namespace std
unsigned count0 class c public c()cout
55
Restricting Object Creation Through Constructors
  • The compiler provides a public default
    constructor for a class with two exception
  • If a class explicitly declares any constructor
  • If a class declares a nonpublic default
    constructor

56
Example 3.5.7
class Emp public Emp(unsigned
ID)idID unsigned id // unique id number
private Emp()// declared privated for
emphasis //.. int main() Emp elvis
//Error emp() is private Emp
cher(111122233) //ok //
57
The Copy Constructor
  • Four types of Constructors
  • 1.Default Constructor
  • 2.Parameterized Constructor
  • 3.Copy Constructor
  • 4.Convert Constructor
  • The copy constructor creates a new object as a
    copy of another object

58
Cont.
  • Two Common prototypes for the copy constructor
  • Person(Person )//Person reference
  • Person(const Person)// Person reference
  • A copy constructor may have more than one
    parameters
  • Person( const Person p, bool marriedfalse)

59
Example 3.5.9
include include using
namespace std class Namelist public Namelist(
)size0 p0 Namelist(const string
,int) void set(const string, int) void
set(const char, int) void dump()
const private int size string p
60
NamelistNamelist(const string s, int
si) pnew stringsizesi for(int
i0iNamelistset(const string s, int
i) pis void Namelistset(const char s,
int i) pis void Namelistdump()const fo
r(int i0i 61
int main() string list"Lab","Husky","Collie
" Namelist d1(list,3) d1.dump()//lab,huskey,
Collie Namelist d2(d1) d2.dump()//lab,huskey,C
ollie d2.set("Great dane",1) d2.dump()//lab,gr
eat Dane,Collie d1.dump()////lab,Great
Dane,Collie return 0
62
Defining a Copy Constructor(1)
d1
size
3
Huskey
Lab
Collie
p
d1.dump Lab Huskey Collie
Namelist d1(list,3)
63
Defining a Copy Constructor(2)
d1
Huskey
Lab
Collie
d2
d2.dump Lab Huskey Collie
Namelist d2(d1)
64
Defining a Copy Constructor(3)
d1
Great
Lab
Collie
d2
d2.set(Great,1)
65
include include using
namespace std class Namelist public Namelist(
)size0 p0 Namelist(const string
,int) Namelist(const Namelist) void
set(const string, int) void set(const char,
int) void dump() const private int
size string p void copyIntop(const
Namelist)
66
NamelistNamelist(const string s, int
si) pnew stringsizesi for(int
i0iconst Namelist d) p0 copyIntop(d) void
Namelistset(const sring s, int
i) pis void Namelistset(const char s,
int i) pis void Namelistdump()const fo
r(int i0i 67
void NamelistcopyIntop(const Namelist
d) delete p if(d.p!0) p new
stringsized.size for(int i0ipid.pi else p0 size0
68
int main() string list"Lab","Husky","Collie
" Namelist d1(list,3) d1.dump()//lab,huskey,
Collie Namelist d2(d1) d2.dump()//lab,huskey,C
ollie s2.set("Great dane",1) d2.dump()//lab,gr
eat Dane,Collie d1.dump()////lab,Husky,Coll
ie return 0
69
d1
d2
70
Disable Passing and Returning by Value for class
Object
  • A class designer may wish to disable copying of
    class objects
  • Because such objects are generally large
  • If the copy constructor is private, top-level
    functions and methods in other classes cannot
    pass or return class objects by value

71
Example 3.5.11
class c public c() private c(c)
void f(c )// call by value c g()
//return by value int main() c c1,c2
f(c1)//errorc(c)is private
c2 g()// errorc(c)is
private //.
72
Convert Constructors
  • A convert constructor for class c is a
    one-argument constructor used to convert a non-c
    type to a c object

73
Example 3.5.12
class person public person()nameunknown
//default person(const string
n)namen//convert person(const char
n)namen//convert //. private string
name int main() person soprano(Dawn
Upshaw) //..
74
The Convert Constructor and Implicit Type
Conversion
  • A convert constructor can be used as an
    alternative to function overloading

75
Constructor Initializers
class C public C() x0//OK, x not
const c0//Error c is not Error
private int x//nonconst data member const int
c//const member
76
Example 3.5.14
class C public C()c(0) x0
private int x//nonconst data member const int
c//const member c
77
Example 3.5.15
class C public C()c(0),x(-1)
private int x//nonconst data member const int
c//const member
78
Constructors and the Operators new and new
  • The Operators new and new have advantages over
    malloc and calloc
  • Use of new and new ensures that the constructor
    will be invoked
  • Use of malloc and calloc does not

79
Example 3.5.16
include // for malloc and calloc
class Emp public Emp()/--------------/ Em
p(const char name) /--------------/ //
int main() Emp elvis new Emp()
//Default Emp cher new Emp(Cher)
//convert Emp lotsofEmps new Emp1000 Emp
foomalloc(sizeof(Emp)) // no constructor //
.
Write a Comment
User Comments (0)
About PowerShow.com