Title: ECE 538 Object Oriented Concepts Session 2
1ECE 538 Object Oriented ConceptsSession 2
- Dr. John G. Weber
- John.Weber_at_notes.udayton.edu
- http//academic.udayton.edu/JohnWeber
2Data Abstraction and Encapsulation
- Central feature of OOP is division of program
into objects - Object is like a black box
- You know the I/O and the control behavior
- You dont know about the internal implementation
or representation - Recall that a C class is the prototype for an
object - One class can lead to many object instances
- When a class is defined, class name becomes a new
data type (object) and definition creates an
instance
3A Simple Class Example
//smallobj.cpp //demonstrates a small simple
object include ltiostreamgt //include the
iostream class //Class definition class
Smallobj //define a class private int
somedata //define data that can only be used
internal to the object public void setdata
(int d) //member function to set data
somedata d void showdata() //member
function to display data on the console
stdcout ltlt "Data is " ltlt somedata ltlt stdendl
//end of class definition--note the
semicolon after the //Main program to
illustrate usingthe smallobj class int
main() Smallobj s1, s2 //define two objects
of class samllobj s1.setdata (1066) //use
setdata member function to set the value of s1
and s2 s2.setdata (1776) s1.showdata() //use
showdata member function to display
data s2.showdata() return 0
4Constructors
- Simple Class used member functions to initialize
object - A constructor allows the object to initialize
itself - Constructor runs automatically
5Sample
//counter.cpp //object represents a counter
variable //uses a constructor to initialize
object include ltiostreamgt //define counter
class class Counter private unsigned int
count //define private variable count as an
unsigned integer public Counter() count(0)
/ empty body / //A constructor void
inc_count() count //member function to
increment the counter int get_count() return
count //member function to return the
count //main program to test Counter class int
main() Counter c1, c2 //define counter
objects c1 and c2 and init both to
zero stdcout ltlt "\nc1 " ltlt
c1.get_count() //display count for obj
c1 stdcout ltlt "\nc2 " ltlt c2.get_count() //di
splay count for obj c2 c1.inc_count() c2.inc_co
unt() c2.inc_count() stdcout ltlt "\nc1 "
ltlt c1.get_count() //display count for obj
c1 stdcout ltlt "\nc2 " ltlt c2.get_count() //di
splay count for obj c2 stdcoutltltstdendl ret
urn 0
6More on Constructors
- Previous example initialized counter to zero
- Suppose you wished to initialize to some other
value - Use the following approach
- Then instantiate the object with data
- Counter c1(5), c2(0)
class Counter private unsigned int
count //define private variable count as an
unsigned integer public Counter(int x)
count(x) / empty body / //A
constructor void inc_count()
count //member function to increment the
counter int get_count() return
count //member function to return the count
7Still More on Constructors
- Constructor Forms
- ClassName() //default constructor inits
object data to zero - ClassName(type var1, type var2, type var n)
//constructor with data - Default constructor included automatically
- If you include another constructor, you must
explicitly include the default if you want it
8Data Hiding
- Objects have data and instructions
- Data members
- Member functions
- Two categories
- Private
- Specified with key word private
- Accessible only by member functions of the same
class - Public
- Specified with key word public
- Accessible from anywhere in program
9Pointers to Objects
- Pointers may point to objects as well as data or
data structures - Useful when we dont know how many objects of a
given class will be created until run time - Suppose we have a class Distance that takes input
of feet and inches and then formats the output - Example shows non-pointer and pointer method of
interfacing with the object
10Pointer to Object Demo
/ englptr.cpp // accessing member functions by
pointer include ltiostreamgt using namespace
std class Distance //English
Distance class private int feet
float inches public void getdist()
//get length from user
cout ltlt "\nEnter feet " cin gtgt feet
cout ltlt "Enter inches " cin gtgt inches
void showdist() //display
distance cout ltlt feet ltlt "\'-" ltlt
inches ltlt '\"' int main() Distance
dist //define a named Distance object
dist.getdist() //access object
members dist.showdist() // with
dot operator Distance distptr
//pointer to Distance distptr new Distance
//points to new Distance object
distptr-gtgetdist() //access object members
distptr-gtshowdist() // with -gt
operator cout ltlt endl return 0
11Defining New Data Types and Operators
- Recall Class can be considered new data type
- Consider developing a vector class
- e.g. class Vector
- public
- double x, y
- Vector() x(0.0), y(0.) //constructor
- Vector() x(double xi, double yi)
-
- A vector is then represented by an ordered pair
- We can also define vector operations
- e.g. vector sum
- Consider two vectors u and v.
- The vector sum of u and v is z where
- z.x u.x v.x and x.y u.y v.y
12Operator Overloading
- C allows us to define new meaning for standard
operators - Called overloading
- Defined in the class definition
- One operand must be part of the class
- Look at the vector sample in the attached zip file
13More on Operators
- Recall Counter Class
- Lets rewrite this using an overloaded prefix
operator
class Counter private unsigned int
count //define private variable count as an
unsigned integer public Counter() count(0)
/ empty body / //A constructor void
inc_count() count //member function to
increment the counter int get_count() return
count //member function to return the count
14// countpp3.cpp // increment counter variable
with operator // uses unnamed temporary
object include ltiostreamgt using namespace
std /////////////////////////////////////////////
/////////////////// class Counter
private unsigned int count
//count public Counter() count(0)
//constructor no args
Counter(int c) count(c) //constructor, one
arg int get_count()
//return count return count
Counter operator () //increment count
count
//increment count, then return return
Counter(count) // an unnamed temporary object
// initialized
to this count //////////////////////////////
//////////////////////////////////
15// countpp4.cpp // increment counter variable
with operator both prefix and postfix // uses
unnamed temporary object include
ltiostreamgt using namespace std //////////////////
////////////////////////////////////////////// cla
ss Counter private unsigned int
count //count public
Counter() count(0) //constructor no
args Counter(int c) count(c)
//constructor, one arg int get_count()
return count //return count member function
Counter operator () //increment
count (prefix operator )
count //increment count, then
return return Counter(count) // an
unnamed temporary object
// initialized to this count
Counter operator () //increment count
(postfix operator )
//return an unnamed temporary object
return Counter(count) // initialized to
this count, then increment count
/////////////////////////
///////////////////////////////////////
16Inheritance
- Maybe most powerful feature of OOP
- Process of creating new classes from existing
classes - New classes called derived classes
- Existing classes are called base classes
- Derived class inherits all capabilities of base
class and can add embellishments - Base class is unchanged
- Why use
- Reusability
- Assume base class is written and tested
- You need to modify
17Example
- Lets consider the counter example as a base
class - Suppose we need a counter object that can be
decremented as well as incremented - Options
- Modify counter again
- Potentially introduce errors
- May not have access to source code
- Use inheritance
- Preserves integrity of counter class
- Works without access to counter source
- We will call our derived class CountDn
- Consider only the prefix operator case first
18Base Class
// countdn.cpp // inheritance with Counter
class include ltiostreamgt using namespace
std /////////////////////////////////////////////
/////////////////// class Counter
//base class protected
//NOTE not private
unsigned int count //count
public Counter() count(0)
//no-arg constructor
Counter(int c) count(c) //1-arg
constructor unsigned int
get_count() const //return count
return count Counter operator ()
//incr count (prefix) return
Counter(count) ////////////////////////
////////////////////////////////////////
19Base Class
- Definition essentially unchanged
- Private vs protected keyword
- Needed to allow member functions of the derived
class to access member functions of the base
class - Hence, to allow inheritance
- Variables which might be used by derived classes
should be declared as protected rather than
private
20Derived Class CountDn
//////////////////////////////////////////////////
////////////// class CountDn public Counter
//derived class public
Counter operator -- () //decr count
(prefix) return Counter(--count)
///////////////////////////////////////////////
/////////////////
- Specify class derived from Counter
- Public keyword in class declaration
- Objects of derived class able to access public
member functions of base class - Note derived class may use private keyword
- Objects of derived class may only access public
members of the derived classnot the base class
21Derived Class Constructors
- How do we initialize CountDn object to a value
- Compiler provides a no-argument constructor
automatically - Will no provide more complex constructor
- Constructors for the derived class
//////////////////////////////////////////////////
////////////// class CountDn public Counter
public CountDn() Counter()
//constructor, no args calls constructor in
base class Counter CountDn(int
c) Counter(c) //constructor, 1 arg calls
constructor in base class Counter
CountDn operator -- () //decr
count (prefix) return
CountDn(--count) ////////////////////////
////////////////////////////////////////
22Overriding Member Functions
- Member functions in a derived class may override
member functions in a base class - Objects of derived class will use derived class
functions of same name as base class functions - Objects of base class will use base class
functions - Derived class functions (of same name as base
class functions) use scope resolution operator to
call base class functions
23Example -- Stack
- Consider the class Stack
- Potential problem can push beyond limit or try
to pop when empty
//////////////////////////////////////////////////
////////////// class Stack protected
//NOTE can't be private enum
MAX 3 //size of stack array
int stMAX //stack array of
integers int top //index
to top of stack public Stack()
//constructor top -1
void push(int var) //put number on
stack sttop var int
pop() //take number off stack
return sttop-- /////////////////
///////////////////////////////////////////////
24Create Derived Class Stack 2
- Use new functions push and pop with error checking
class Stack2 public Stack public
void push(int var) //put number on stack
if(top gt MAX-1) //error
if stack full cout ltlt "\nError
stack is full" exit(1)
Stackpush(var) //call push() in Stack
class int pop()
//take number off stack
if(top lt 0) //error if stack empty
cout ltlt "\nError stack is empty\n"
exit(1) return Stackpop() //call
pop() in Stack class
25Design with Inheritance
- Looked at inheritance as a way to add
functionality to classes - Consider it now as a design methodology
- Example Employee Data Base
- Base Class Employee
- Includes employee name and employee number
- Derived Class 1 Manager
- Includes title and organizational element
- Derived Class 2 Scientist
- Includes Number of Publications
- Derived Class 3 Laborer
- No additional data for this class
26ExampleBase Class Employee
- class employee //employee
class -
- private
- char nameLEN //employee
name - unsigned long number //employee
number - public
- void getdata()
-
- cout ltlt "\n Enter last name " cin gtgt
name - cout ltlt " Enter number " cin gtgt
number -
- void putdata() const
-
- cout ltlt "\n Name " ltlt name
- cout ltlt "\n Number " ltlt number
-
-
27Derived Class Manager
class manager public employee //management
class private char titleLEN
//"vice-president" etc. char
orgLEN //Organization
public void getdata()
employeegetdata() cout ltlt " Enter
title " cin gtgt title cout ltlt
" Enter organization " cin gtgt org
void putdata() const
employeeputdata() cout ltlt "\n
Title " ltlt title cout ltlt "\n
Organization " ltlt org
28Derived Class Scientist
class scientist public employee //scientist
class private int pubs
//number of publications public
void getdata()
employeegetdata() cout ltlt " Enter
number of pubs " cin gtgt pubs
void putdata() const
employeeputdata() cout ltlt "\n
Number of publications " ltlt pubs
29Derived Class -- Laborer
class laborer public employee //laborer
class
- Note This class adds no new data to the
employee class
30Main Program
int main() manager m1, m2 scientist
s1 laborer l1 cout ltlt endl
//get data for several employees cout ltlt
"\nEnter data for manager 1"
m1.getdata() cout
ltlt "\nEnter data for manager 2"
m2.getdata() cout ltlt "\nEnter data for
scientist 1" s1.getdata() cout ltlt
"\nEnter data for laborer 1" l1.getdata()
//display data for
several employees cout ltlt "\nData on manager
1" m1.putdata()
cout ltlt "\nData on manager 2"
m2.putdata() cout ltlt "\nData on scientist
1" s1.putdata() cout ltlt "\nData on
laborer 1" l1.putdata() cout ltlt endl
return 0
31Abstract Base Class
- No objects of base class defined
- Employee class was general and used for a base
- Laborer class identical to employee class
- Emphasizes all classes derive from same
abstract class - If additional info on laborers required in
future, add to laborer class
32UML Class Diagram
33Multiple Inheritance
34Multiple Inheritance
- Class student //base class
- Class employee //base class
- Class manager public employee, public student
- Class scientist public employee, public student
- Class laborer public employee
35Assignment 2
- Code an run the examples from this session
- Implement the multiple inheritance example on the
previous charts
36Assignment 2 (cont)
- Develop a Vector Class which supports the
following Vector operations for three dimensional
vectors - Addition
- Subtraction
- Dot product
- Scaler times a vector
- Vector divided by a scaler
- Cross product
- Magnitude
- Normalize (divide vector components by magnitude)
- Reverse (reverses direction of vector)
- Overload normal arithmetic operators as required
to implement above operations
37Assignment 2 (cont)
- Develop a matrix class for 3x3 matricies which
supports the following operations - Transpose
- Inverse
- Addition
- Subtraction
- Multiplication
- Determinant
- Multiplication by a scaler
- Division by a scaler
- Matrix times a vector
- Vector times a Matrix
- Overload operators as required to implement above
operations - Create a test program using these classes to
verify correct operation