Title: CS1102C Bridging course
1CS1102C Bridging course
- Kiruthika Ramanathan
- Kiruthika_r_at_nus.edu.sg
2Course outline
Date Venue Lesson
5th Dec/12th Dec LT6 Object Oriented Design
6th Dec/13th Dec LT6 Basic C
7th Dec/14th Dec LT6 Classes
7th Dec/14th Dec Cales PC Cluster Lab 1 Intro to OOP
8th Dec/ 15th Dec LT6 Inheritance and overloading
9th Dec/16th Dec LT6 Data structures a primer
9th Dec/16th Dec Cales PC Cluster Lab 2 Advanced OOP with C
3Bridging course objectives
- Understanding and implementation Object Oriented
Programming - Competent programming with C
- Preparation for CS1102C with primer lectures on
data structures
4Contents
- Objected Oriented Design
- Basic C
- Classes
- Inheritance
- Operator overloading
- Intro to Data Structures
- 1 Linked lists and stacks
- 2 Recursion and sorting
- 3 Binary Trees
5Object oriented analysis
Object oriented analysis is based upon concepts
that we first learnt in kindergarten objects and
attributes, classes and members, wholes and
parts. Why it has taken us so long to apply these
concepts to the analysis and specification of
information systems is anyones guess perhaps
we have been too busy following the flow during
the heyday of structured analysis to consider the
alternatives ?
6A short Intro
- Objects Everything goes around them
- Focus on defining the objects (a car for eg)
- Characteristics
- Manipulations
- Behaviours
- etc
- Modular programming
7A short Intro
- Data modelling
- Classes
- Encapsulation
- Inheritance
8Why should I learn OOP
- Even if u dont work now with OOP, one day you
will - More oop capabilities in Language
- Java and C are common but there are more OOP
add ons to other langiages - OOP techniques in PERL is quite hot
- VB.net is supposed to be fully Obj oriented
- OOP does give an edge.
9OOP definitions
Object Oriented Programming programs which are oriented around objects. Encapsulation, Polymorphism, and Inheritance increase code reuse and decrease code maintenance
Class Defines the variables the methods common to all objects of a certain kind.
Object An instance of a class. A class must be instantiated into an object before it can be used in the software.
Encapsulation The act of placing data and the operations that perform on that data in the same class. The class then becomes the 'capsule' or container for the data and operations.
10OOP definitions
Inheritance Reuse of base classes (superclasses) to form derived classes (subclasses).
Coupling The degree of mutual interdependence between modules/components. Lower coupling gt more reusable methods. Keep coupling to a minimum but not zero
11OOP Definitions
Visibility The ability to 'see' parts of an object from outside. Lower visibility is better.
Dependency The degree that one component relies on another to perform its responsibilities. Lower dependency is better.
12Example 1
- Objective System to draw figures
- Objects The figures to be drawn (circle, square,
rectangle, triangle etc) gt circle object, square
object etc - Each object has an operation draw inside it
Method draw - c.draw() is a different method from s.draw().
- Method draw is encapsulated in class
Encapsulation The act of placing data and the
operations that perform on that data in the same
class. The class then becomes the 'capsule' or
container for the data and operations.
13Example 1 contd
- Objective System to draw figures
- With top down design
14Functional vs Object decomposition
Functional decomposition emphasizes the
operations Object oriented decomposition
emphasizes the role of the objects c.draw()
versus draw(cir) OOP gives a cleaner
separation No ripple effect Eg If you want to
add a line to the list of figures to draw, then
Main() circle c, square s, line l c.draw() s.draw() l.draw() void draw(FIG) if FIGcircle draw a circle else if FIGline draw a line else end if
15Exercise 1
Objective Implement a draw figure system and
take into consideration the input arguments, i.e,
circle radius, square length, rectangle length
and breadth. and returns the area and perimeter
of the figures. Come up with an OOP and top down
design pseudo codes. Hint To include variables
in a class you define the variables as you define
a method
16Creating Objects
- Abstraction Focus on the essential aspects
17Creating Objects
- Properties of a good abstraction
- Well named
- Name must reflect the nature of the abstraction
- Coherence
- Related attributes from the viewpoint of user
- Accuracy
- Object must not be supernatural to the domain
- Minimal
- Attributes of objects must be just what is
required. - Redundancy is not encouraged
- Complete
- Whatever is needed must be there
18Exercise 2
- Come up with some abstractions of Automobile
from the point of view of - Manufacturer
- Owner
- Are your abstractions
- gt Well named, coherent, accurate, minimal, and
complete?
19Seperation
- Distinguish between goal and the means to achieve
- User is interested in end product
- Developer is interested in both the back end and
the front end - Need for seperation??
20Seperation
The same implementation can be used for different
interface. Implementation is the union of
interface requirements
21Exercise 3
- Explain how separation is used in the following
cases - Telephone
- Postal delivery serve
- Stereo
- Restaurant
- How is separation used in
- An operating system
- A web browser
- A compiler
22Example 2 Furniture Class
Furniture chair, table chair.locationloc1 chair.
move(loc1,loc2) table.weight10 int table_weight
table_weightTable.weigh()
int furnitureweigh() return weight
23Brief Intro to inheritance
Derived Class
Base Class
24Brief Intro to inheritance
class sofas public furniture int
cushionNumber
class furniture int cost int
dimension int weight
include sofas.h" int main() sofas
cornerSofa cornerSofa.cost50
cornerSofa.cushionNumber2
Base Class
25Advantages of OOP
- Easier maintenance. Objects may be understood as
stand-alone entities - coupling a measure of module dependency
- inter-module coupling minimized by keeping
message flow as low as possible - cohesion a degree of localization in a module
- cohesion maximized by maintaining object details
(data functions) localized w.i. an object
26Advantages of OOP
27Advantages of OOP
- Reusability Objects are reusable components
inheritance also enhances reusability - For some systems, there may be an obvious
mapping from real world entities to system
objects - Ability to tackle larger problem domains - handle
complexity by abstraction (data abstraction,
procedural abstraction, class abstraction)
28Conclusion
- Object Oriented Programming vs Top down design
- OOP advantages
- Some definitions
- Abstraction and Separation
- You should now be able to come up with some
simple OO designs
29Your first OOP system
- Consider a system that models the function of a
library. You can consider a virtual library, for
instance. - What objects would you find useful in an OO
design of this system? - What methods would you find useful in an OO
design of this system? - How would a top down design of this system work?
30Contents
- Objected Oriented Design
- Basic C
- Classes
- Inheritance
- Operator overloading
- Intro to Data Structures
- 1 Linked lists and stacks
- 2 Recursion and sorting
- 3 Binary Trees
31Basic C and VC
- Some new operators and extensions in C
- Construct a simple linked list program from start
to finish
32Functions/Methods
int move (int startPoint, int Endpoint)
return distanceMoved //definition also serves
as declaration int main()
distancemove(start,end)
int move (int startPoint, int Endpoint) //
prototyping must be done in advance before the
function is called int main()
distancemove(start,end) int move (int
startPoint, int Endpoint) return
distanceMoved
33Overloading Functions
- Same names functions with different input
parameters
void print(int i) printf(First Overload
d\n, i) void print (int i, int j)
printf(Second Overload i i\n, i,j) int
main() print(7) print(7,10)
34Did You realize?!?
- Operators are overloaded!!
float float1, float2 sum1float1float2
int int1, int2 sum2int1int2
The operator for float1float2 is different
from the plus operator for int1int2 In fact, all
operators can be overloaded with a few
exceptions. We will discuss this further later in
the course
35Exercise 1 Passing By reference
void move (point q) --q.x q.y int
main() point p int a5, b-12 p.xa p.y
b move(p) printf("xd, yd\n", p.x,
p.y)
struct point int x, y
What is the output??
36New operators in C
- Scope Resolution
- Storage allocation new
- Storage release delete/ delete
-
37Scope Resolution
- x External scope
- clm Class scope
- float x
- void f(int n)
-
- float x //local x (this is the auto value)
- x1.5 //fs x
- x2.5 //extern x
38new and delete
- Like malloc and free in c
- new is used to allocate storage dynamically
- Syntax
- new followed by type
- new int //allocates storage for 1 int
- If allocation is not possible, then new int 0
- int_ptrnew int
- versus
- int_ptr(int )malloc(sizeof(int))
39new and delete
- delete frees storage allocated by new.
- Syntax
- int_ptrnew int
- delete int_ptr
- OR
- int_ptrnew int50
- delete int_ptr
- WARNING!!!!DONOT USE C storage management with
the C functions. - i.e, malloc delete is not good
- nor is new free
40Example of New and Delete Linked Lists
- We are going to make a linked list of elephants.
- Each elephant will have a name
41So what is a linked list??
- Each element keeps a pointer to the next element
on the list - struct elephant
-
- char name50
- elephant next
Each elephant has a element that points to the
next elephant
42Visual of a linked list
43The elephant list ?
- Three functions
- elephant get_elephants()
- Returns the pointer to the first elephant
- The first elephant points to the second elephant
and so on - print_elephants(elephant ptr)
- void free_list(elephant ptr)
- Frees the storage allocated to the elephants
44Main function
- int main()
-
- elephant start
- startget_elephants()
- print_elephants(start)
- free_list(start)
-
-
- return EXIT_SUCCESS
45Creating the elephants list
- elephant get_elephants()
-
- elephant currentnew elephant
- elephant firstcurrent
- int response
- printf("\n\n\tName ")
- scanf("s", current-gtname)
- printf("\n\n\n\tAdd Another? (1yes, 0No))
") - scanf("d", response)
-
46Creating the elephant list continued
- while (response)
-
- if((current-gtnextnew elephant)0)
-
- printf("Out of memory")
- return(first) //return whatever we have at
the moment -
- currentcurrent-gtnext
- printf("\n\n\tName ")
- scanf("s", current-gtname)
- printf("\n\n\n\tAdd Another? (1yes, 0No))
") - scanf("d", response)
-
- current-gtnext0
- return(first)
-
47Printing the elephants
- void print_elephants(elephant ptr)
-
- int count1
- printf("\n\n\n")
- while(ptr !0)
-
- printf ("\nElephant number d is s",
count,ptr-gtname) - ptrptr-gtnext
-
48Freeing the list
- void free_list (elephant ptr)
-
- elephant temp_ptr
- while (ptr!0)
-
- temp_ptrptr-gtnext
- delete ptr
- ptrtemp_ptr
-
49C I/O
- Include iostream.h
- Use cin and cout to read and write to screen
- Ex 1
- float x
- cin gtgt x
- cout ltltx2
- Ex 2
- float x
- cout ltlt'\n'
- cin gtgt x
- cout ltltx2 ltlt'\n'
streams vs stdio
50const vs. define
- define size 30
- const int size30
-
- include ltiostream.hgt
- const int size30
- main()
-
- int size2size
- size22
- coutltltsize2 ltlt " "ltltsize ltlt'\n'
-
- NOTE!! size will give an error!!
51Conclusions
- Some revision on C and introduction to some of
the C extensions - Functions and overloading
- Passing by reference
- , new, delete operators
- Creating and manipulating linked lists
- The cin and cout streams
52Contents
- Objected Oriented Design
- Basic C
- Classes
- Inheritance
- Operator overloading
- Intro to Data Structures
- 1 Linked lists and stacks
- 2 Recursion and sorting
- 3 Binary Trees
53Creating Classes
- Syntax of classes is similar to the syntax of
structs - class testClass
-
- int integer
- float pseudo_real
-
- struct testStruct
-
- int integer
- float psuedo_real
-
54Classes continued
- Class has several data members
- Data members defined inside the class declaration
- Methods can be defined inside the class
declaration. - A class only describes the storage required gt
does not allocate storage
55Example of a class
- class Win
-
- int id
- short x,y
- short width, height
- char visible
- public
- void moveWin(short, short)
- char getName()
- void minwin() width0
-
- //Creating Objects
- Win win1, win2, lots_of_wins100000
56Example of a class continued
- Win win1, win2, lots_of_wins100000
- storage is allocated in accordance with the class
declaration - win1 has storage for int id, short data members
x, y, width, height etc - Three methodsgt moveWin, getName, and minWin
- minWin is defined inside the declaration
57Example of a class continued
- moveWin is declared but not defined inside Win
- To define moveWin elsewhere, use the scope
resolution operator - void WinmoveWin(short new_x, short new_y)
-
- xnew_x
- ynew_y
-
- Scope resolution operator indicates that moveWin
belongs to the Win class.
58Classes continued
- By default, anything that is declared inside a
class are private - class Win
-
- int id
- short x,y
- short width, height
- char visible
- public
- void moveWin(short, short)
- char getName()
- void minwin() width0
private
public
59Private vs Public
- Private Data members and methods can only be
accessed by - Methods of the same class moveWin and getName
- Friend functions (will be covered later)
60Example Private vs Public
- void f (Win w) //f is not a Win method
-
- coutltltw.widthltltendl
- //this is illegal since w.width is private.
- w.minWin()
- //this is legal since minWin has been declared
as a public method.
61Class declarations styles and conventions
Typically place the data members together and the
methods together But this will still work
- class C
-
- float r //defaults to private
- public
- int m1() //public
- float m2() //public
- private
- char c //private
- public
- void m3() //public
- int z //public data member!!
-
62Creating classes with struct keyword
- struct Win_S
-
- int id
- short x,y
- short width, height
- char visible
- void moveWin(short, short)
- char getName()
- void minwin() width0
-
63Difference between class and struct
- The final result is the same
- NOTE
- members are public by default when using struct
- Members are private by default when using class.
64Exercise 1
- Write a declaration for class Employee that has
at least six data members and at least six
methods. - Write code slices that define Employee objects
and invoke each of the methods.
65Example Stacks
- Abstract data type
- Zero or more elements
- insertions and deletions occur at the same end gt
at the top - Create a Stack class with methods that allow the
user to - Push an element onto the stack
- Pop an element off the stack
- Print all the stack elements top to bottom
66Stacks continued
- Ensure stack integrity
- Check that stack is not full before pushing
- Check stack is not empty before popping
- Information hiding
- Stacks internal representation is made private
- Encapsulation
- Including methods within a stack
67Intro to Enumeration
- used to set up collections of named integer
constants. - define SPRING 0
- define SUMMER 1
- define FALL 2
- define WINTER 3
- OR
- enum SPRING, SUMMER, FALL, WINTER
- enum SPRING0, SUMMER1, FALL2, WINTER3
68Stack Implementation
- const int MaxStack10000
- const char EmptyFlag'\0'
- class Stack
-
- enumFullStackMaxStack,EmptyStack-1
- enumFalse0, True1
- char itemsMaxStack
- int top
public void dump_stack() int full() int
empty() char pop() void push(char) void
init()
69Stack Implementation Continued
- void Stackinit()
-
- topEmptyStack //EmptyStack is -1
-
- void Stackpush(char c)
-
- if (full())
- return
- itemstopc
70Stack Implementation Continued
- char Stackpop()
-
- if (empty())
- return EmptyFlag //you cannot pop a stack if
it is empty - else
- return itemstop--
-
- int Stackempty()
-
- if (topEmptyStack)
-
- cerrltlt"Stack Empty"ltltendl
- return True
-
- else
- return False
71Stack Implementation Continued
- int Stackfull()
-
- if (top1FullStack)
-
- cerrltlt"Stack full at"ltltFullStackltltendl
- return True
-
- else
- return False
-
- void Stackdump_stack()
-
- for (int itop igt0 i--)
-
- coutltltitemsiltltendl
-
72Stack Implementation Continued
- include "Stack.h"
- include ltiostream.hgt
- int main()
-
- Stack s1
- s1.init()
- s1.push('a')
- s1.push('b')
- cout ltlts1.pop()ltltendl
- s1.push('c')
- cout ltlts1.pop()ltltendl
- s1.push('d')
- s1.push('e')
Output b c e d a
73Constructors and Deconstructors
- In the stack program we had to do
- stack.init().
- If the above is forgotten, then stack initializes
some junk value. - Constructors do automatic initialization
- Programmer writes the constructor implementation
but does not call constructor
74Stack constructor
- void StackStack()
-
- topEmptyStack
-
- There is no need for the init() function.
- In the main program do
- Stack s1 //constructor is automatically invoked
75More info about constructors
- Default constructor takes in no arguments
- Class can have more than one constructor
- But the compiler and not the programmer invokes
the constructor - Constructor name is the same as the class name.
- Constructors dont usually have a return value
- Constructors MUST be public. WHY??
76Overloaded constructors
- class Color
-
- float red
- float green
- float bluel
- public
- Color() //default constructor
- Color(float, float, float) //parameterized
77Constructor definitions
- ColorColor()
-
- red0.0
- green0.0
- blue0.0
-
- ColorColor(float r, float g, float b)
-
- redr greeng blueb
78Calling different constructors
- include Color.h
- //always include the class headers
- main
-
- //using the default constructor
- Color c1
- //using the second constructor
- Color c2(1.0, 0.5, 0.0)
-
79Parameterized constructors with constants
- ColorColor(float r, float g0.5, float b0.0)
-
- redr greeng blueb
-
- you can call this constructor with one or more
parameters - Color c2(1.0, 0.5, 0.0)
- Color c3(1.0, 0.5) //b is initialized to 0.0
80Constructors and dynamic storage
- class ex1
-
- char text
- public
- ex1()
-
- ex1ex1()
-
- textnew char20
- strcpy(text, Hi world)
-
- //call
- ex1 example
81Deconstructor
- const long OneBillion1000000000
- class BigStr
-
- char string
- long size
- public
- BigStr()
- BigStr() //deconstructor
82Deconstructors
- BigStrBigStr()
-
- string new charOneBillion1
- for (long i0 iltOneBillion i)
- stringi''
- stringOneBillion'\0'
- sizeOneBillion
-
- BigStrBigStr()
-
- delete string
- cout ltlt "destructed string"ltltendl
83Deconstructors
- Free any storage the constructor allocates when
object is destroyed - Object can be destroyed by using delete operator
Or when object goes out of scope - Otherwise the storage becomes garbage.
- Compiler does not provide a deconstructor if you
donot write one - Constructors and deconstructors donot return any
value. - How many deconstructors can a class have??
84Constructors and deconstructors Example Zipcode
- Objective
- Create a class ZipC which manipulates Zip codes
of different lengths. - Zip code can be generated by either a integer or
a string. - Practice points
- Information hiding the datamembers are private
- Encapsulation include various methods in the
ZipC class - Revision on new and delete operators
- Some new c operations and functions introduced
85ZipCode main function
- include "ZipC.h"
- include ltstdlib.hgt
- int main()
-
- ZipC zip("60363-1312")
- ZipC zip2(15124877)
- ZipC zip3
- zip.write()
- zip2.write()
- zip3.write()
- return EXIT_SUCCESS
86The ZipCode class ZipC
- const int MinZip5
- const int MaxZip32
- const int InitChar'?'
- include ltiostream.hgt
- include ltstring.hgt
- include ltstdio.hgt
class ZipC char code //private public Zip
C() ZipC(const char ) ZipC(const unsigned
long) ZipC() void write()
87Constructor 1 default constructor
- ZipCZipC()
-
- codenew charMinZip1
- for (int i0 iltMinZip i)
- codeiInitChar
- codei'\0'
-
88Constructor 1 default constructor
- Constructors set code to storage dynamically
using the new operator. - Default constructor allocated only MinZip1
- Call using
- ZipC zip1
- (No arguments) so the default constructor is used
89Conditional operator
- The conditional operator (? ) is a ternary
operator (it takes three operands) - The first operand is implicitly converted to
bool. It is evaluated and all side effects are
completed before continuing. - If the first operand evaluates to true (1), the
second operand is evaluated. - If the first operand evaluates to false (0), the
third operand is evaluated.
90Conditional operator continued
- include ltiostream.hgt
- int main()
-
- int i 1, j 2
- cout ltlt ( i gt j ? i j ) ltlt " is greater." ltlt
endl -
91Constructor 2string argument
- ZipCZipC(const char zipstr)
-
- int len len(strlen(zipstr)ltMaxZip)?strlen(zipst
r)MaxZip - codenew charlen1
- strncpy(code, zipstr,len)
- //copy first len chars of zipstr into code
- codelen'\0'
92Constructor 2string argument
- Converts traditional c string to ZipC object.
- Constructor only allocates the necessary space
using len.
93Constructor 3 integer argument
- ZipCZipC(const unsigned long zipnum)
-
- char bufferMaxZip1
- sprintf(buffer, "ld", zipnum)
- codenew charstrlen(buffer)1
- strcpy(code, buffer)
94Constructor 3 integer argument
- Use sprintf to convert the integer to null
terminated array of char. - Use a buffer with MaxZip storage to anable the
conversion. - Then allocate only the necessary number of char
cells.
95deconstructor
96deconstructor
- Deallocates whatever storage is given to
constructor. - If the bytes were not deallocated they will
become garbage ? - gt Program cannot access them.
97Write function
- void ZipCwrite()
-
- coutltltcodeltltendl
-
- //Note that code is defined as private in the
constructor. The main function cannot access it.
98The output
- int main()
-
- ZipC zip("60363-1312")
- ZipC zip2(15124877)
- ZipC zip3
- zip.write()
- zip2.write()
- zip3.write()
- return EXIT_SUCCESS
-
99Summary
- Introduction to classes
- Creating classes
- Private vs public
- Classes vs structs
- Making a stack class
- Constructors and deconstructors
100Contents
- Objected Oriented Design
- Basic C
- Classes
- Inheritance
- Operator overloading
- Intro to Data Structures
- 1 Linked lists and stacks
- 2 Recursion and sorting
- 3 Binary Trees
101Operator Overloading
- 2/3 (integer division)0
- 2.0/3.0 (floating point division)0.66667
- Having the same / operator simplifies
manipulation - Sample application Complex number class
102Operator overloading continued
- class String
-
- char string
- public
- String operator(const String)
-
- String Stringoperator(const String s)
-
- //code that defines the concatnation of two
strings
103Operator overloading continued
- class String
-
- char string
- public
- int operatorgt(const String s)
-
- int Stringoperatorgt(const String s)
-
- return strcmp(string,s.string)gt0
104Operator overloading continued
- s1.stringlettuce
- s2.stringlattice
- if (s1gts2)
-
- ..
105The class Complex
- Implement complex numbers as an abstract data
type - Must support standard binary operations such as
addition and multiplication - Create complex with two double data members real
and imag
106The class complex
- class numComp
-
- double real
- double imag
- public
- void printcomp()
- numComp operator(numComp c) //operator
-
- numComp(double, double)
- numComp(double)
- numComp()
107The complex operator
- numComp numCompoperator (numComp c)
-
- return numComp(realc.real,imagc.imag)
-
- Overloading extends standard arithmetic operators
to Complex Numbers.
108The complex operator
- numComp numCompoperator (numComp c)
-
- return numComp(realc.real,imagc.imag)
-
- int main()
-
- numComp c1(7.7, 5.5)
- numComp c2(4.4, 3.3)
- numComp c3
- c3c1c2 //invokes the complex operators
- c3.printcomp()
109The complex operator
- numComp numCompoperator (numComp c)
-
- return numComp(realc.real,imagc.imag)
-
- c1c2
- You are calling c1 with c2 as argument.
- Same as
- c3c1.operator (c2)
- c in the method refers to c2
110Exercise
- Overload the and / operators for the class
numComp
111Friends
- class eg1
-
- char string
- public
- eg1(char S) //constructor
-
- stringnew charstrlen(s)1
- strcpy(string, s)
-
-
- int main()
-
- eg1 c1(hello)
- int lenstrlen(c1.string) // THIS IS AN ERROR
WHY??
112Friends
- class eg1
-
- char string // string is a private datamember
cannot be accessed from outside class eg1 - public
- eg1(char S) //constructor
-
- stringnew charstrlen(s)1
- strcpy(string, s)
-
-
- int main()
-
- eg1 c1(hello)
- int lenstrlen(c1.string) //ERROR
113Friends
- class eg1
-
- char string
- eg1(char S) //constructor
-
- stringnew charstrlen(s)1
- strcpy(string, s)
-
- friend int strlen(char ) // strlen is a friend
of eg1 class. -
- int main()
-
- eg1 c1(hello)
- int lenstrlen(c1.string) // Now there is no
problems ?
114Example Complex Stack
- Implement the stack class designed for complex
objects rather than chars - The method dump_stack() must access both the
complex class and the stack class - class ComplexStack
-
-
- int top
- Complex itemsmaxStack
115Example Complex Stack
- class Complex // because ComplexStack has
Complex items, make class complex visible to
class Complex stack - class ComplexStack
-
-
- int top
- Complex itemsmaxStack
- public
- ..
- friend void dump_stack(ComplexStack)
116Example Complex Stack
- class Complex
-
- double real
- double imag
- public
- friend void dump_stack(ComplexStack)
117Example Complex Stack
- void dump_stack(ComplexStack s)
-
- for (int itop igt0 i--)
-
- coutltlts.itemsi.realltlt ltlts.itemsi.imag
-
- coutltltendl
118Example Complex Stack
- void dump_stack(ComplexStack s)
-
- for (int itop igt0 i--)
-
- coutltlts.itemsi.realltlt ltlts.itemsi.imag
- //s is a stack item
-
- coutltltendl
119Example Complex Stack
Item5.real Item5.imag
TOP
Item5
Item4
Item3
Item2
Item1
Item0
s.items5.real
120Friends continued
- Dump_stack is a friend of complex stack and a
friend of complex - Use of friend functions
- Allow a library function to access private
members of a class - Allow a function to access private members of two
or more classes
121Friend classes
- Friend Functions can be a method in a class OR a
toplevel method - class F
-
- int adm
- public
- int f()
-
- class ex1
-
- int cdm
- public
- int m()
- friend int t() //toplevel friend
- friend int Ff()// fs friend method clarify
using the scope resolution
122Friend classes
- If you want many methods of class F to access the
datamembers of class ex1, then you can make the
whole class a friend - class F
-
-
-
- class C
-
- friend F //Any method in F has full access to
methods in C
123Friend classes
- class F
-
-
-
- class C
-
- friend F
-
- F is a friend of class C
- C is nota friend of F C can only access Fs
public info. - Symmetrical relationship has to be explicit
- Not transitive gt if P is a friend of Q and Q is
a friend of R, P is not a friend of R unless it
is explicitly declared
124Assertions Program correctness
- Condition that must be true at some particular
point in the programs execution - Id an assertion fails, the sytem detects and
reports the error. - Usually there are preconditions and
postconditions for a method. - Assertions are used in these cases
125AssertionExample Stack push and pop
- void Stackpush(char c)
-
- assert(!full()) //assert that the stack is not
full - itemstopc
- assert(!empty())
-
- INSTEAD OF
- void Stackpush(char c)
-
- if (full())
- return
- itemstopc
-
126Assertion contd
- assert(!full())
- Evaluates the expression !full().
- If expression is true, execution proceeds
normally - If expression is false, program terminates.
- The file assert.h must be included to implement
assertions
127Method pop, asserted
-
- char Stackpop()
-
- char val
- assert(!empty())
- val itemstop--
- assert(!full())
- return val
128Summary
- Operator Overloading
- Friends
- Assertions
129Contents
- Objected Oriented Design
- Basic C
- Classes
- Inheritance
- Operator overloading
- Intro to Data Structures
- 1 Linked lists and stacks
- 2 Recursion and sorting
- 3 Binary Trees
130Example A Binary Tree
- Implement a binary search tree as a class
- Each node contains a data
- Data is arranged such that
- For any node N, the data in the left subtree are
ltN - Data in the right subtree are gtN
- Use BSTs to implement sorting and recursion
- Revise the pertinent concepts so far.
131BST illustration
All the values in the left of a node are less
than or equal to the node value. All the values
on the right of the node are greater than the
node value
132Traversing a BST
- InOrder
- Preorder
- PostOrder
- When traversing a tree, a node can be visited 3
times - 1st time Pre Order
- 2nd time In order
- 3rd Timr Post Order
133BST implementation
- Two classes
- Node
- BST
- BST is a friend to Node
- Illustrate
- Information hiding
- All the data members are private
- Encapsulation
- Methods in BST and node
134List versus tree implementation
- class elephant
-
- char name
- elephant next
-
- class node
-
- char val
- node lc //left child
- node rc //right child
-
Points to next node
Points to two nodes, left and right
135Class Node
- const char None' '
- class node
-
- friend BST
- char val
- node lc //left child
- node rc //right child
- public
- void write()
- int empty()
- node()
136Node method definitions
- nodenode()
-
- lc0
- rc0
- valNone //A node is always initialized with an
empty space -
- int nodeempty()
-
- return valNone //1 if the node is empty, 0
otherwise -
- void nodewrite()
-
- cout ltltval
137BST class
- class BST
-
- node root
- node tree
- void inorderAux(node)
- void addNodeAux(const char v)
- public
- void inorder()
- void addNode(const char)
-
- BST()
138BST methods
- BSTBST()
-
- roottreenew node
-
- void BSTaddNode(const char v)
-
- treeroot //start at the root always
- addNodeAux(v)
-
- void BSTinorder()
-
- inorderAux(root)
-
139BST methods contd
- void BSTinorderAux(node n)
-
- //if the current subtree is empty, it means
there are no nodes. So return. - if (n-gtempty())
- return
- inorderAux(n-gtlc) //traverse the left subtree
- n-gtwrite() //visit and write the node
- inorderAux(n-gtrc) //traverse the right subtree
140BST methods contd
- void BSTaddNodeAux(const char v)
-
- //if the root of the current subtree is empty,
store v there. - // And create a left and a right subtree
- if (tree-gtempty())
-
- tree-gtvalv
- tree-gtlcnew node
- tree-gtrcnew node
- return
-
- //otherwise, search either the left or the right
subtree to store the value - if (vlttree-gtval)
- treetree-gtlc
- else
- treetree-gtrc
- addNodeAux(v) //invokes itself
-
141Calling the BST
- include "BST.h"
- int main()
-
- BST bst
- bst.addNode('K')
- bst.addNode('G')
- bst.addNode('F')
- bst.addNode.(R)
- bst.addNode('I')
- bst.addNode('H')
- bst.inorder()
142Summary of the BST
- Implement BST as a friend of node
- All private members of node can be accessed by
BST - The node constructor initializes the node to
empty and makes sure there are no children - The nodewrite() writes the value of the node
- The nodeempty() returns whether the node is
empty . This means there are no children
143Summary of the BST continued
- The BST constructor creates a new node and points
the root and the tree to it. - The node is initialized with the node constructor
- Root always points to the root of the tree
(start) and the tree points to the current
subtree - Add node sets the tree to root
- Allows search to start at the root of the entire
tree - addNodeAux stores the value, then creates a left
and right child - If the subtree is not empty, then set it to the
left or right and invokes itself.
144Summary of BST continued
- Once the BST is created, inorder is used to
perform inorder traversal of tree - Recursive method
- Traverses the nodes left subtree
- Prints all the values
- Traverses the nodes right subtrees
145Visual BST
146Design Exercise
- Design an OO system to implement a BST of complex
numbers - You need to consider how to
- Declare a complex object in a node
- Compare two complex numbers when implementing
addNode (try operator overloading) - What classes will BST need to be a friend of?
What classes will node need to be a friend of?
147Exercise
- Implement the preorder traversal of the BST
- In the preorder traversal, the BST visits the
node, prints a value and then moves to the left
node - i.e, the value is printed the first time the node
is visited.
148Inheritance
- Inheritance allows for code reusage.
- Code written for one class can be used by other
classes in the heirarchy - If code is correct for a class, it is correct for
all inherited classes - Program is more robust
149Basic concepts and syntax of inheritance
- Base class, derived class
- Consider class vehicle.
- Every car is a vehicle
- Car is a derived class from vehicle
- Car is also a subclass of vehicle
- Vehicle superclass/base class
- Car subclass/ derived class
150Direct and indirect inheritance
- A car is a vehicle
- A BMW is a car
- BMW is a direct subclass of car
- BMW is an indirect subclass of vehicle
151Multiple inheritance
- Car is a subclass of both vehicle and
expensiveToy gt one subclass, many superclass - Vehicle has two subclassesgt car and truck gt one
superclass, many subclass
152Review of member accessibility
- Datamembers and methods can be
- Public global access
- Private access by the class alone or by friends
- Protected access by
- Methods within the class
- Methods within the class hierarchy (derived
classes) - Friend functions
153Accessibility example
- class pen
-
- public
- void set_pen(int a, int b)
- void move_pen(int a, int b)
- pen()
- virtual pen()
- protected
- void initial_pen()
- private
- int x
- int y
154Accessibility continued
- include "pen.h"
- int main()
-
- pen p
- p.set_pen(0,0) //no problems ? this is a global
member - p.initial_pen() //error protected member
- p.x0 //error private member
-
155Deriving classes syntax
- class B
-
- .
-
- class D access-specifier B
-
- ..
156Access specifier
- Either public, private or protected
- Controls the access provided to the derived class
- Defaults to private if omitted
- Derived class CANNOT prohibit any inheritace
- Derived class can specify additional data members
or methods.
157Inheritance and access specifiers contd
- Class Vehicle
-
- public
- float mph
- float cost
- float weight
-
- Class Car public vehicle
-
- Public
- char brand_name100
-
158Inheritance and access specifiers contd
Inherited from vehicle
Local to car
159Inheritance and access specifiers contd
- Public derivations
- public member in base class is public in derived
class - protected member in base class is protected in
derived class - Private member in base class is private in base
class visible only in base class.
160Public derivations
- class B
-
- public
- int x
- protected
- int w
- private
- int z
-
- class D public B
-
- public
- int y
- void set_w(int a) wa
161Public derivations
member Access Status in D How obtained
X Public From class B
W Protected From class B
Z Not Accessible From class B
Y Public Added by class D
set_w public Added by class D
162Public derivations
- int main()
-
- D d1
- d1.x33 //no problem x is public in B
- d1.y99 //no problem y is public in D
- d1.w77 //ERROR w is protected in B and D
- d1.z88 // ERROR z is private
163Inheritance and access specifiers contd
- Protected derivations
- Public member is protected
- Protected member is protected
- Private member is private in the base class, and
cannot be acessed
164Public derivations
- class B
-
- public
- int x
- protected
- int w
- private
- int z
-
- class D protected B
-
- public
- int y
165Protected derivations
member Access Status in D How obtained
X Protected From class B
W Protected From class B
Z Not Accessible From class B
Y Public Added by class D
166Inheritance and access specifiers contd
- Private derivations
- Public member is private in derived class
- Protected member is private in derived class
- Private member is private in the base class, and
cannot be acessed - Derivation is private by default
167Public derivations
- class B
-
- public
- int x
- protected
- int w
- private
- int z
-
- class D private B
-
- public
- int y
168Private derivations
member Access Status in D How obtained
X Private From class B
W private From class B
Z Not Accessible From class B
Y Public Added by class D
169Indirect inheritance
- class Animal
-
- protected
- char species100
- float lifeExpectancy
- int warmBlooded
class Cat public Animal protected float
favPrey Class houseCat public Cat char
toys10 char catDoctor50 char owner50
170Indirect inheritance
- class Animal
-
- protected
- char species100
- float lifeExpectancy
- int warmBlooded
class Cat public Animal protected float
favPrey Class houseCat public Cat char
toys10 char catDoctor50 char owner50
Animal 3 members Cat 4 members houseCat 7
members 3 added 1 direct inheritance
3 indirect inheritance
171Access declarations
- class BC
-
- protected
- int x
- int y
- public
- int z
172Access declarations
- class DCprivate BC
-
- int w
-
- What are the visibilities of x,y and z in DC??
173Access declarations
- class BC
-
- protected
- int x
- int y
- public
- int z
174Access declarations
- class DCprivate BC
-
- protected
- BCx
- public
- BCz
- int w
-
- X is now protected and z is public.
175Name hiding
- class B
-
- public
- int x //Bx
-
- class Dpublic B
-
- public
- int x // this is dangerous. This x hides the
Bx
176Name hiding
- int main()
-
- D d1
- d1.x999 //this refers to Dx not Bx
177Name hiding
- int main()
-
- D d1
- d1.B1x4 //this refers to B1s x in D1
-
- Use of scope resolution operator
- Very clumsy but it works
178Name hiding in methods
- If a derived class adds a method with th same
name as the base class, the added method hides
the base classs method.
179Name hiding in methods
- class B
-
- public
- void h(float) Bh
-
- class Dpublic B
-
- void h(char ) //Bs h is hidden
180Name hiding in methods contd
- int main()
-
- d d1
- d1.h(Hello) //you are calling Dh
- d1.h(707.7) //this is an error. Bs h is hidden
- d1.Bh(707.7) //this is fine since the scope
is resolved
181Multiple Inheritance
- Derived class has multiple base classes
- class Win
-
- ..
-
- class ScrollWin public Win
-
- int horizontal
- int vertical
-
182Multiple Inheritance
- class ScrollWin public Win
-
- int horizontal
- int vertical
-
-
- class PopupMenu
-
- protected
- int menuChoices
-
- class ScrollPopupMenu public PopupMenu, Public
ScrollWin -
- ..
- //multiple inheritance class
183Exercise
- Can a class class1 be both a base class and a
derived class? Illustrate. - In the code slice
- class A
-
- int x
-
- class B A
-
- int y
-
- main() b b1
- How many data members can b1 access?
184Exercise
- class A
-
- int x
-
- class BA
-
- int y
- void f() yx
-
- Is the above code legal?
185Exercise
- class A
-
- protected
- float f1, f2
- public
- int x
-
- class B private A
-
- public
- void pf1() cout ltltf1ltltendl
int main() B b1 b1.f13.14
b1.pf1() b1.x(int) b1.f1
What is legal? What is not legal?
186Summary
- Inheritance
- Direct and Indirect inheritance
- Access declarations in inheritance
- Name hiding
187