Title: Chapter 2 Objects and Classes
1Chapter 2Objects and Classes
22.1 What is OO programming?
- Object
- an atomic unit/entity that has structure and
state - each object defines operations that may access or
manipulate that state - Information hiding Black-box analogy
- Encapsulation grouping of data and functions
- Inheritance allows extending functionality of an
object.
32.2 Basic Class Syntax
- Class members either data or functions and
categorized into either public, protected, or
private. - Public visible to an instance of (object) a
class - Private visible only inside an instance of a
class - Protected similar to private but visible to
derived classes. - Default all members are private
4An example of a class (1)
- class IntCell
- public
- IntCell()storedValue0
-
- IntCell(int initialValue)
- storedValue initialValue
-
- int read() return storedValue
-
- void write(int x) storedValue x
- private
- int storeValue
- Each instance of IntCell class an IntCell
object contains a single data member named
storedValue. - There are 4 function members, or called member
functions or methods. Two of them are known as
constructors. The other 2 are read and write.
5An example of a class (2)
- class IntCell
- public
- IntCell()storedValue0
-
- IntCell(int initialValue)
- storedValue initialValue
-
- int read() return storedValue
-
- void write(int x) storedValue x
- private
- int storeValue
- Notice the 2 labels public and private. These
labels determine visibility of class members. A
public member may be accessed by any method in
any class. A private member may only be accessed
by methods in its class. In this example, only
storedValue is private, everything else is
public. - By declaring data members to be private, we can
restrict access to internal details of a class,
while methods intended for general use are made
public. This is known as information hiding.
6An example of a class (3)
- class IntCell
- public
- IntCell()storedValue0
-
- IntCell(int initialValue)
- storedValue initialValue
-
- int read() return storedValue
-
- void write(int x) storedValue x
- private
- int storeValue
- A constructor is a special method that describes
how an instance of the class is constructed. If
no constructor is explicitly defined, one that
initializes the data members using language
defaults is automatically generated. The IntCell
class defines 2 constructors. The 1st one is
called if no parameter is specified. The 2nd one
is called if an int parameter is provided, and
uses that int to initialize the storedValue
member.
7A better code (1)
class IntCell public explicit
IntCell(int initialValue 0)
storedValue(initialValue)
int read() const return storedValue
void write(int x) storedValue x
private int storeValue
- Although the above class works, there is some
extra syntax that makes for better code. 4
changes are shown on the left. - Default Parameters The constructor illustrates
the default parameter. As a result, there are
still 2 constructors. One accepts an
initialValue. The other is 0-parameter
constructor, which is implied because
initialValue is optional by having a default
value (implicit empty constructor).
8A better code (2)
class IntCell public explicit
IntCell(int initialValue 0)
storedValue(initialValue)
int read() const return storedValue
void write(int x) storedValue x
private int storeValue
- Initializer List The constructor uses an
initializer list prior to the body of the
constructor to initialize the data members
directly. This can save time in the case where
the data members are class types that have
complex initializations. - In some cases it is required. For instance, if a
data member is const (meaning that it is not
changeable after the object has been
constructed), then it can only be initialized in
the initializer list.
9A better code (3)
class IntCell public explicit
IntCell(int initialValue 0)
storedValue(initialValue)
int read() const return storedValue
void write(int x) storedValue x
private int storeValue
- Normally, a one-parameter constructor defines an
implicit type conversion. - IntCell obj 37 // ok, implicit conversion
IntCell obj IntCell(37) - explicit Constructor The IntCell constructor is
explicit. This is to avoid behind-the-scenes type
conversions. - IntCell obj 37 // illegal
- intCell obj intCell (37) // ok
- intCell obj(37) // ok
10A better code (4)
class IntCell public explicit
IntCell(int initialValue 0)
storedValue(initialValue)
int read() const return storedValue
void write(int x) storedValue x
private int storeValue
- Constant Member Function A member function that
examines but does not change the state of its
object is an accessor. A member function that
changes the state is a mutator because it mutates
the state of the object. - By default, all member functions are mutators.
- The const signifies an accessor only after a
closing parenthesis .
11Constructors
- Member functions that describe how an object is
declared and initialized. - If no constructor defined, compilers will
generate one called default constructor. - Explicit constructors prevent automatic type
conversion. - Initializer list
- Save time
- Data member is const
- Data member is a class type that has no
zero-parameter constructor.
12Constant Functions
- Constant functions functions that do not change
any data member, i.e. accessors - const is a part of the function signature.
- const return_type name(const parameter_list)
const
13Separation of Interface and Implementation
- Interface describes what can be done to the
object, i.e. the header. - Implementation represents internal processes
specified by the interface.
14Interface
Implementation
- ifndef _IntCell_H_
- define _IntCell_H_
- class IntCell
- public
- explicit IntCell(int initialValue 0)
-
- int read() const
-
- void write(int x)
- private
- int storeValue
-
- endif
- Figure 2.4 IntCell.h
- include IntCell.h
- IntCellIntCell(int initialValue 0)
- storedValue(initialValue)
-
- int IntCellread() const
- return storedValue
-
- void IntCellwrite(int x) storedValue x
- Figure 2.5 IntCell.cpp
Scope operator
15Big three Destructor, Copy Constructor, and
Operator
- Destructor tells how an object is destroyed and
free resource when it exits scope. - calling delete, closing files.
- IntCell()
- Copy Constructor allows a new object construct
using the data in an existing one. - For a declaration with initialization,
- IntCell BC or IntCell B(C)
- When an object is passed using call by value
- When an object is returend by value
- Operator copy assignment, copies data members
using by default. ? may cause shallow copying. - this Predefined pointer pointing at the current
object.
16- //destructor
- IntCellIntCell()
- // copy constructor
- IntCellIntCell(const IntCell rhs)
- storedValue(rhs.storedValue)
- // operator
- const IntCell IntCelloperator(const IntCell
rhs) - if(this ! rhs) // standard alias test
- storedValue rhs.storedValue
- return this
-
- Figure 2.7 The defaults for the Big Three
17 - class IntCell
- public
- explicit IntCell(int initialValue 0)
- stored Value
- new int( initialValue)
-
- int read() const
- returen storedValue
-
- void write(int x)
- storedValue x
-
- private
- int storeValue
-
- Figure 2.8
- the data member is a point the defaults are no
good
int f() IntCell a(2) IntCell ba IntCell
c cb a.write(4) cout ltlt a.read() ltlt endl
ltlt b.read() ltlt endl ltlt c.read() ltlt
endl return 0 Figure 2.9 Simple function
that exposes problem in Figure 2.8
182.3 Additional C Features
- Operator overloading extending the types to
which an operator can be applied. - ., ., ?, sizeof cant be overloaded
- Overloading functions must have different
signatures, (return type is not a part of the
sig.) - Type conversion creates a temporary object of a
new type - int a 5 double b a //implicit cast
- Conversions are not transitive.
- (Assume that A, B, and C have diff. Types)
- A cast to B and B cast to C gt A cast to C????NO
192.5 Exceptions
- An exception
- an object that stores information transmitted
outside the normal return sequence\ - used to signal exceptional occurrences, such as
errors - Handle exceptions by throw and catch clauses.
202.6 String Class
- C string array of character terminated by \0
- C standard string a STL class with all
overload operators and built-in functions
Hello world!\0
C string
21string Class Interface
- mystring.h
- In class
- 3 constructors and a destructor
- string(char ch)
- string(const char cstring)
- string(const string str )
- Three states
- int strLength, int bufferLength, char buffer
- 2 accessors
- (copy operator), (indexing operator),
- 2 mutators
- (append operator), (indexing operator)
22string Class Implementation
23Recap
- vectorltstringgt array(100) // 100 calls
- string ptr1 new string // 1 call
- string ptr2 new string(hello) // 1 call
- string ptr3 new string(s)// 1 call
- string ptr4 new string100 // 100 calls
- string ref s // no call
24Composition
- Classes are being used as data member for other
classes - class employee
- public
- void setValue(const strig n, double s)
- name n salary s
-
- void print(ostream out cout) const
- out ltlt name ltlt ( ltlt salary ltlt )
-
- private
- string name
- double salary
25- ostream operatorltlt ( ostream out,
- const Employee rhs )
- rhs.print(out)
- return out
-
- int main()
- vectorltEmployeegt v(3)
- v0.setValue(Bill Clinton, 200000.00)
- v1.setValue(Bill Gates, 2000000000.00)
- v2.setValue(Billy the Marlin, 60000.00)
-
- for(int i 0 i lt v.size() i)
- coutltltviltltendl
- return 0
-
- Figure 2.28 Illustration of composition
26Common errors (Page 87)
- Forgetting to free memory in a destructor
- Constant class members can be initialized only in
the constructor initialize list. - Incorrect parameter passing
-
27In class exercise
- When is it acceptable not to provide a
destructor? - Some compilers complain if a classs members are
all private and has no friends. Why? - What is the difference between a copy constructor
and a copy assignment operator?
28Summary
- Construction/ destruction of objects
- Copy semantics
- Input/output operations
- Overloading
- Implicit/explicit type conversion
- Information hiding/atomicity
29Homework
- Finish reading Chapter 2
- Preview Chapter 3