Title: C for Java Programmers
1C for Java Programmers
- Virtual functions and abstract classes
21. Virtual Functions
- A virtual function is a member function that is
declared within a base class and redefined by a
derived class. - Its looks just like a normal function but has the
keyword virtual preceding it. - So the virtual function defines the form of the
interface. - The derived class redefines it and implements its
operation as it relates specifically to it.
3Why Virtual Functions are Useful
- So you can just use virtual functions as you
would any other function. - However what makes them so implortant is how they
behave when accessed by a pointer. - When a base-class pointer points to a derived
object that contains a virtual function, C
decides which version of that function to call
based on the type of object pointed to. - This is all processed at run-time.
4Example
- include ltiostream.hgt
- class base
- public
- virtual void vfunc() coutltltThis is the base
vfunc().\n -
- class derived1 public base
- public
- virtual void vfunc() coutltltThis is a dervied
function\n -
- class derived2 public base
- public
- virtual void vfunc() coutltltSo is this
one.\n
5Example in Action
- int main()
- base p
- base b
- derived1 d1
- derived2 d2
-
- pb
- p-gtvfunc()
- pd1
- p-gtvfunc()
- pd2
- p-gtvfunc()
A pointer to the parent class
OUTPUT This is a base vfunc(). This is a
derived function. So is this one.
6Pure Virtual Functions
- Think about the concept of a Shape.
- Shapes will be manipulated by our programs, they
will be put in lists, assembled, - We can think about triangles, rectangles,
irregular shapes even projections of higher
dimensional objects.
A shape is anything that can be displayed on the
screen. It has the characteristics position and
orientation. It can be translated, rotated and
scaled. It can be displayed and deleted.
7Pure Virtual Functions
A shape is anything that can be displayed on the
screen. It has the characteristics position and
orientation. It can be translated, rotated and
scaled. It can be displayed and deleted.
- A specific shape, e.g. a rectangle may have its
own methods. - But the implementation of the functions
translate, rotate, scale, display,
delete will - Be present in each shape.
- Differ from shape to shape.
- Furthermore, they do not have any meaning at the
level of the shape class.
8Pure Virtual Functions
A shape is anything that can be displayed on the
screen. It has the characteristics position and
orientation. It can be translated, rotated and
scaled. It can be displayed and deleted.
- class shape
- float positionx
- float positiony
- float orientation
- public
- shape(float posx, float posy, float angle)
- virtual void translate(int deltax, int deltay)
0 - virtual void rotate(float delta) 0
- virtual void scale(float factor) 0
- virtual void display() 0
- virtual void delete() 0
9Pure Virtual Functions
A shape is anything that can be displayed on the
screen. It has the characteristics position and
orientation. It can be translated, rotated and
scaled. It can be displayed and deleted.
- class rectangle public shape
- float length
- float width
- float color
- public
- shape(float posx, float posy, float angle)
- virtual void translate(int deltax, int deltay)
- virtual void rotate(float delta)
- virtual void scale(float factor)
- virtual void display()
- virtual void delete()
10Pure Virtual Functions
A shape is anything that can be displayed on the
screen. It has the characteristics position and
orientation. It can be translated, rotated and
scaled. It can be displayed and deleted.
- void display(shape s)
- s-gtdisplay()
-
- void main()
- list ltshape gt A(10)
- A.push_back(new rectangle())
- A.push_back(new circle())
- A.push_back(new projection())
-
- for_each(A.begin(), A.end(), display)
-
-
11Abstract Classes
- A class that contains at least one pure virtual
function is said to be abstract it has a
virtual function in it that has no definition at
all. - Because of this no objects of the abstract class
can be created. - It is an incomplete type a foundation for
derived classes. - However you can still create a pointer to an
abstract class.
12More Virtual
- Consider the following code segment
void main() shape T10 T0 new
rectangle() T1 new circle() T2 new
square() T9 new diamond() for
(int I0Ilt10I) delete TI
- What exactly does the delete operator do?
- Which destructor is being called?
13Virtual Destructors
- If the destructor in the shape class has not been
declared virtual, only this shape class
destructor will be called.
class shape int colors public
shape() delete colors class
polygon shape coordinates
vertices public polygon() delete
vertices
class shape int colors public virtual
shape() delete colors class polygon
public shape coordinates vertices public
virtual polygon() delete vertices //
virtual is in fact automatic as it is in the base
class
14Virtual Functions Implementation
- Implementation of virtual functions is through
tables. - Dereferencing a pointer to a virtual method leads
to a table of function pointers embedded in the
object. - Most compilers offer optimisation options
concerning these tables (e.g. smart virtual
function tables) - This is a more complicated issue than the
inline concept.
15Example 1
- We will build a framework for string encoding.
16vide.hh
- class vide
- public
- virtual void code(char ) 0
-
17vides.hh
- class pivot public vide
-
- char pivotElementLower
- char pivotElementHigher
- public
- pivot(char)
- void code(char s)
-
- class filler public vide
-
- public
- void code(char s)
-
- class swapper public vide
-
- public
- void code(char s)
-
18vides.c
- void fillercode(char s)
-
- char last ''
- while (s)
-
- if (isspace(s)) slast
- else last s
- s
-
19vides.c
- void swappercode(char s)
-
- while (s)
-
- if (islower(s)) s'a''z'-s
- if (isupper(s)) s'A''Z'-s
- s
-
20vides.c
- pivotpivot(char pe)
-
- if (!isalpha(pe)) pe 'm'
- pivotElementLower
- tolower(pe)
- pivotElementHigher
- toupper(pe)
-
- void pivotcode(char s)
- while (s)
-
- if (islower(s)) s 'a'
(pivotElementLower 'z' -'a' - s)('z'-'a') - else if (isupper(s)) s 'A'
(pivotElementHigher 'Z' - 'A' - s)('Z'-'A') - s
-
-
21videmo.c
- int main()
- vide list10
- list0 new filler
- list1 new swapper
- list2 new pivot('m')
- list3 new pivot('n')
- list4 new pivot('l')
- list5 new pivot('o')
- list6 new pivot('k')
- list7 new pivot('p')
- list8 new pivot('q')
- list9 new pivot('d')
char input30 cin.getline(input,30) for
(int i0ilt10i) char toCode30
strcpy(toCode,input) listi-gtcode(toCode)
cout ltlt i ltlt " " ltlt toCode ltlt endl
listi-gtcode(toCode) cout ltlt i ltlt " "
ltlt toCode ltlt endl return 0
22Videmo run
- 0 AAthinggoffbeauty
- 0 AAthinggoffbeauty
- 1 Z gsrmt lu yvzfgb
- 1 A thing of beauty
- 2 M sfeyg xh limrsn
- 2 A thing of beauty
- 3 N tgfah yi mjnsto
- 3 A thing of beauty
- 4 L redxf wg khlqrm
- 4 A thing of beauty
- 5 O uhgbi aj nkotup
- 5 A thing of beauty
6 K qdcwe vf jgkpql 6 A thing of beauty 7 P
vihcj bk olpuvq 7 A thing of beauty 8 Q wjidk
cl pmqvwr 8 A thing of beauty 9 D jvupw ox
cydije 9 A thing of beauty
23Example 2
- A framework for assistance in deciphering a coded
string
24codemo.c
- int main()
- vide list10
- char name1030
- list0 new filler
- strcpy(name0,"Filler")
- list1 new swapper
- strcpy(name1,"Swapper")
- list2 new pivot('m')
- strcpy(name2,"Pivot around m")
- list3 new pivot('n')
- strcpy(name3,"Pivot around n")
- list4 new pivot('l')
-
-
25codemo.c
- char buffer256
- strcpy(buffer,"This message makes sense")
- list5-gtcode(buffer)
- codeCheck cH(10)
- for (int i 0ilt10i)
- cH.add(namei,listi)
- cH.doCheck(buffer)
26codeCheck
- class codeCheck
- struct pair
-
- char name30
- vide encoder
-
- pair list
- int numberOfEncoders
- public
- codeCheck(int n)
- void add(char ,vide )
- virtual void doCheck(char s)
-
27codeCheck.c
- codeCheckcodeCheck(int n)
-
- list new pairn
- numberOfEncoders 0
-
- void codeCheckadd(char n, vide v)
-
- listnumberOfEncoders.encoder v
- strcpy(listnumberOfEncoders.name,n)
-
28codeCheck.c
- void codeCheckdoCheck(char s)
-
- char buffer new charstrlen(s)
- for (int i0iltnumberOfEncodersi)
-
- strcpy(buffer,s)
- listi.encoder-gtcode(buffer)
- cout ltlt listi.name ltlt " " ltlt buffer ltlt
endl -
29Codemo run
- Filler Uhgvvckvvoikkcoekvvvkbvk
- Swapper Fste xpeelrp xlvpe epyep
- Pivot around m Rfgq kcqqxec kxicq qclqc
- Pivot around n Sghr ldrryfd lyjdr rdmrd
- Pivot around l Qefp jbppwdb jwhbp pbkpb
- Pivot around o This message makes sense
- Pivot around k Pdeo iaoovca ivgao oajoa
- Pivot around l Uijt nfttbhf nblft tfotf
- Pivot around q Vjku oguucig ocmgu ugpug
- Pivot around d Ivwh bshhous boysh hschs
30Example 3
- In the previous example, too much work is done in
the application area. - Let us try to extend the framework such that the
following program becomes possible.
31codemoX.c
- void main()
- codeCheckX myCheck(10)
- filler f("A filler",myCheck)
- swapper s("A swapper",myCheck)
-
- pivot pk('k',"A pivot around k",myCheck)
- char buffer256
- strcpy(buffer,"This message makes sense")
- pk.code(buffer)
-
- myCheck.doCheck(buffer)
-
32codemoX run
- A filler Qdcrrxgrrkeggxkagrrrgwrg
- A swapper Jwxi ctiipvt cpzti itdit
- A pivot around m Vjku oguucig ocmgu ugpug
- A pivot around n Wklv phvvdjh pdnhv vhqvh
- A pivot around l Uijt nfttbhf nblft tfotf
- A pivot around o Xlmw qiwweki qeoiw wirwi
- A pivot around k This message makes sense
- A pivot around p Ymnx rjxxflj rfpjx xjsxj
- A pivot around q Anoy skyygmk sgqky yktyk
- A pivot around d Mabl fwllsyw fsdwl lwglw
33The videX in the application
class pivot public videX char
pivotElementLower char pivotElementHigher
public pivot(char, char , codeCheckX )
void code(char s)
- class filler public videX
-
- public
- filler(char ,codeCheckX )
- void code(char s)
-
- class swapper public videX
-
- public
- swapper(char , codeCheckX )
- void code(char s)
34videsX.c
- fillerfiller(char n,
- codeCheckX cH)
- videX(n,cH)
- void fillercode(char s)
- char last ''
- while (s)
- if (isspace(s)) slast
- else last s
- s
-
swapperswapper(char n, codeCheckX cH)
videX(n,cH) void swappercode(char s)
while (s) if (islower(s))
s'a''z'-s if (isupper(s))
s'A''Z'-s s
35videsX.c
- pivotpivot(char pe, char n,
- codeCheckX cH)
- videX(n,cH)
-
- if (!isalpha(pe)) pe 'm'
- pivotElementLower
- tolower(pe)
- pivotElementHigher
- toupper(pe)
- void pivotcode(char s)
-
- while (s)
-
- if (islower(s)) s 'a'
(pivotElementLower - 'z' -'a' - s)('z'-'a')
- else if (isupper(s)) s 'A'
(pivotElementHigher - 'Z' - 'A' - s)('Z'-'A')
- s
-
-
36videX.hh
- class codeCheckX
- class videX
- char name30
- codeCheckX myCH
- public
- videX(char , codeCheckX )
- virtual void code(char ) 0
37videX.c
- include "videX.hh"
- include "codeCheckX.hh"
- videXvideX(char nm, codeCheckX cH)
-
- cH-gtadd(nm, this)
- strncpy(name,nm,30)
38codeCheckX.hh
- class codeCheckX
- struct pair
-
- char name30
- videX encoder
-
- pair list
- int numberOfEncoders
- public
- codeCheckX(int n)
- void add(char ,videX )
- virtual void doCheck(char s)
-
39codeCheck.c
- codeCheckXcodeCheckX(int n)
-
- list new pairn
- numberOfEncoders 0
-
- void codeCheckXadd(char n, videX v)
-
- listnumberOfEncoders.encoder v
- strcpy(listnumberOfEncoders.name,n)
-
40codeCheck.c
- void codeCheckXdoCheck(char s)
-
- char buffer new charstrlen(s)
- for (int i0iltnumberOfEncodersi)
-
- strcpy(buffer,s)
- listi.encoder-gtcode(buffer)
- cout ltlt listi.name ltlt " " ltlt buffer ltlt
endl -
41QUESTIONS