Title: Chapter 3 Classes
1Chapter 3Classes
- Richard JohnsonBaugh
- Martin Kalin
- Reporterwangwei
2Outline
- 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
33.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
4Class declaration
- Classes Declarations
- In C, A class is a data type
- A Class declaration creates a class as a data type
5Example 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
6Class 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
7Create 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
8Class 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
9Extend 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
-
10Information 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
11Example 3.1.4
Class person Public void setAge(unsigned
n) unsigned getAge() const Private unsigned
age
12The Member Selector Operator
- Access to any class member
- Member selector operator .
- Class indirection operator -
13Example 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
14Example 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
15Class 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
16Example 3.1.7
Class c Public void m()//public
scope Private char d //class scope(private
scope)
Class z Int x
17The difference between the Keywords class and
struct
- Class
- All members default to private
- Struct
- All members default to public
18Example
Class c int x void m()
Struct c int x void m()
19Defining 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
20Example 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
21Using Classes in a Program
- 1. the class declarations
- 2. Object definitions
- 3. Client requests for services
22A 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()
233.2 Sample ApplicationA Stack Class
- Problem
- Create a Stack class that supports pushes and
pops of ints
24Sample Output
25C Implementation
26Discussion
- Stack class encapsulates six high-level,public
methods that constitute its inter face - Init
- Push
- Pop
- isFull
- isEmpty
- dump
273.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
28The First
- Classes and Objects make up the core of OOP
- They are powerful but potentially inefficient
- To Introduce ways in efficient ways
29Passing 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
30Example 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
31include using namespace std class
C public void set(int n)numn int
get()const return num private int
num void f(c) c g()
32int 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
33Object References as const Parameters
class C public void setName(const string
n) namen //.other public members private st
ring name
34Cont.
- 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
35Const Methods
- If the method does not change an objects data
members - Directly
- Indirectly
- Invoking other methods that changes the objects
state
36Example 3.3.2
class C public void set(int n)numn int
get()const return num private int num
37Cont.
- 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
38Example 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
39Example 3.3.4 the class
class C public void set (const string
n)namen const string get() const return
name private string name
40Cont. 3.3.4
- Three const
- In method set,parameter
- Const method get()
- Return a const reference
41Overloading 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
423.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
433.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
443.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
45The 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
46Constructors
- 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
47Example 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
48Constructors
- 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
49Example 3.5.3
include person.h int main() person
anonymous //Default constructor person
jc(J.Coltrne)// parameterized
constructor //
50Constructors
- 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
51Example 3.5.4
include stack.h int main() stack
s1 s1.push(89)//Trouble top not initialized
class Stack stack()init()//ensures
initialization
52Example 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
53Arrays 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
54Example 3.5.6
include using namespace std
unsigned count0 class c public c()cout
55Restricting 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
56Example 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 //
57The 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
58Cont.
- 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)
59Example 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
60NamelistNamelist(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
61int 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
62Defining a Copy Constructor(1)
d1
size
3
Huskey
Lab
Collie
p
d1.dump Lab Huskey Collie
Namelist d1(list,3)
63Defining a Copy Constructor(2)
d1
Huskey
Lab
Collie
d2
d2.dump Lab Huskey Collie
Namelist d2(d1)
64Defining a Copy Constructor(3)
d1
Great
Lab
Collie
d2
d2.set(Great,1)
65include 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)
66NamelistNamelist(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
67void NamelistcopyIntop(const Namelist
d) delete p if(d.p!0) p new
stringsized.size for(int i0ipid.pi else p0 size0
68int 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
69d1
d2
70Disable 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
71Example 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 //.
72Convert Constructors
- A convert constructor for class c is a
one-argument constructor used to convert a non-c
type to a c object
73Example 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) //..
74The Convert Constructor and Implicit Type
Conversion
- A convert constructor can be used as an
alternative to function overloading
75Constructor 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
76Example 3.5.14
class C public C()c(0) x0
private int x//nonconst data member const int
c//const member c
77Example 3.5.15
class C public C()c(0),x(-1)
private int x//nonconst data member const int
c//const member
78Constructors 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
79Example 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 //
.