Title: C for Java Programmers
1C for Java Programmers
- Lecture 15
- C for Windows Programming
2What you might have missed
- We finished the Section
- Algorithms
- Exceptions
- Java vs. C A fight to the death
- C 7 Deadly sins
3Further C
- Today (and probably later)
- An explanation of Virtual Functions
- Virtual inheritance
- Memory leaks and exceptions
- Windows Programming
- The Old Fashioned Way
- The Object Orientated Way
- Microsoft Foundation Classes
41. 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.
5Why 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.
6Example
- 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
7Example 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.
8Pure 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.
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.
- 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.
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.
- 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
11Pure 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()
12Pure 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)
-
-
13Abstract 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.
14More 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?
15Virtual 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
16Virtual 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.
17Inheritance
- Let us shortly come back to the concept of
inheritance. - In C the base class is present through an
object of this class within each object of the
derived class.
class base public int b class derived
public base public float d void main()
derived o
18Multiple Inheritance
- In case of multiple inheritance, this goes for
each of the base classes
class base1 class base2 class derived
public base1, public base2 void main()
derived o
object o
object of class base1
object of class base2
19Multiple Inheritance
- And if the base classes derive themselves
object o
object o
class base1 public base class base2
public base class derived public base1,
public base2 void main() derived o
base2 object
base object
20Multiple Inheritance
- This is what you would expect in many cases.
- Example
- A box of objects is implemented as an array of
pointers to objects with adding, traversing and
removing functionality. - A team is a box of objects (persons) with
coordinating functionality - A job is a box of objects (tasks) with
constraints - A teamJob is a team as well as a job describing
how a job may be performed by a team
21Multiple Inheritance
22Multiple Inheritance
- But not in all cases
- Example
- A uI is a user interface
- A dialog is a uI to retrieve data from the user
- A fancy is a uI with a special appearance
- A fancyDialog is a dialog and a fancy
- It is clear from this definition that we do not
need the datastructures for uI twice. - Conceptually this makes perfect sense however
23Multiple Inheritance
24Virtual Inheritance
class uI class dialog public virtual uI
class fancy public virtual uI class
fancyDialog public dialog , public fancy
virtual
virtual
25Virtual Inheritance
fancyDialog object
uI object reference
object o
fancy object
virtual
virtual
uI object reference
dialog object
uI object reference
26Memory, leaks and exceptions
- Remember
- If you use dynamic memory, you are responsible
for allocating is as well as for freeing it. - One way to do it is allocating upon entry of a
block and freeing it upon leaving the block (java
fashion)
void f() aClass p new aClass() delete
p
27Memory, leaks and exceptions
- However
- This does not make perfect sense
- Dynamic memory lives independently from the
blockstructure of your program. - The previous example is better written as follows
void f() aClass p new aClass() delete
p
void f() aClass p()
28Memory, leaks and exceptions
- However
- The problem becomes manifest if an exception
occurs
void g() trhow(e) void f() aClass p
new aClass() g() // memory is not
freed delete p
void g() trhow(e) void f() aClass
p() g() //stack cleanup will call
destructor of aClass for object p!
29Memory, leaks and exceptions
- Conclusion
- Memory allocation is best done in constructors
- It must be deleted in corresponding destructors
- Any error you want to handle MUST be caught
between allocation and deallocation occurring in
the same block.
void f() aClass p new aClass() try
g() // may throw an exception catch
(exception e) delete p // free memory //
handle error e delete p
302. Windows Programming
- WinMain() called by Windows at the start of
execution of the program. - WindowProc() a procedure for each window class
defined, which will be called by the OS whenever
a message is to be passed to the applications
window. - WinMain() contains the message loop for
retrieving messages that have been queued for the
application. - WindowProc() handles the ones that arent queued
it handles all communications with the user by
processing the Windows messages generated by
clicks, mouse movement or keypresses.
31Windows API
- The Windows Application Programming Interface
comes as part of every copy of Windows. - Consists of a large set of functions to your
application that provide all the services and
communication with windows. - It actually contains 1000s of functions.
- For every windows program you write the
interactions between it and the user are handled
by windows. - Info is received by the program second-hand
through Windows Messages.
32Windows Programming
Windows API
Windows
Program Start
API Calls
Messages
- WindowsProc()
- Process all the messages that windows is sending
- WinMain()
- Initialise variables
- Define windows
- Create Windows
Our Program
33C and the Windows API
- The Windows API was not written with C or
Visual C in mind. - The API needs to be used with lots of languages
and so its not OO it doesnt recognise class
objects. - Your Windows programming environment works around
this though. - For example Visual C uses MFC (Microsoft
Foundation Classes) to encapsulate the API in a
way that makes it easy to use.
34A Window The Old Fashioned Way
- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE
prevInstance, LPSTR lppCmdLine, int nCmdShow) -
- WNDCLASS WindowClass
- static char szAppName OFWin
- HWND hWnd
- MSG msg
- WindowClass.style CS_HREDRAW CS_VREDRAW
- WindowClass.lpfnWndProc WindowProc
- WindowClass.cbClsExtra 0
- WindowClass.cbWndExtra 0
- WindowClass.hInstance hInstance
- WindowClass.hIcon LoadIcon(0,
IDI_APPLICATION) - WindowClass.hCursor LoadCursor(0, IDC_ARROW)
- WindowClass.hbrBackground static_castltHBRUSHgt(
GetStockObject(GRAY_BRUSH)) -
35WinMain() The Old Fashioned Way
- WindowClass.lpszMenuName 0
- WindowClass.lpszClassName szAppName
-
- Register.lpszClassName szAppName
-
- hWnd CreateWindow
- szAppName,
- A Basic Window the Old Fashioned Way,
- WS_OVERLAPPEDWINDOW,
- CW_USERDEFAULT,
- CW_USERDEFAULT,
- CW_USERDEFAULT,
- CW_USERDEFAULT,
- 0,
- 0,
- hInstance,
- 0
-
36WindowProc() Old Style
- long CALLBACK WindowProc (HWND hWnd, UINT
message, WPARAM wParam, LPARAM lParam) -
- HDC hDC
- PAINTSTRUCT PaintSt
- RECT aRect
-
- switch(message)
-
- case WM_PAINT hDC BeginPaint(hWnd,
PaintSt) - GetClientRect(hWnd, PaintSt)
- SetBkMode(hDC, TRANSPARENT)
- Draw Text hdC,Holy Cow Batman...a window
with text!, - -1, aRect, DT_SINGLELINEDT_CENTERDT_V
CENTER) -
37YukIt goes on
- EndPaint(hWnd, PaintSt)
- return 0
- case WM_DESTROY
- postQuitMessage(0)
- return 0
- default
- return DefWindowProc(hWnd, message, wParam,
1Param) -
-
- Enter all this as source code and include
ltwindows.hgt at the top and you will have a fully
functioning C windows program.
38The End Result
39Microsoft Foundation Classes
- The MFC are a set of predefined classes upon
which windows programming is built in VC. - These classes represent an OO way of
encapsulating the windows API. - A Visual C Windows program involves creating
and using MFC objects, or classes derived from
them. - These classes have methods for communicating with
windows, for processing Windows messages and for
sending messages to each other.
40Microsoft Fried Chicken (MFC)
Microsoft Foundation Classes (MFC)
Mansfield Football Club (MFC)
- The key to MFC and windows program is all tied up
with the concept of INHERITANCE. - All of the grunt work necessary for a windows
program to work exists in the base classes of
MFC, and we just inherit their properties. - All we do is add data and function members that
customise the classes to suit the functionality
that our program needs.
41Deciphering Visual C Code
This is a subliminal Message
If you buy Jim Beer.
You will get better marks
- All the classes in MFC have names beginning with
the letter c - CDocument
- CView
- Any Data Members of an MFC classes are prefixed
with the letter m - m_pMainWnd
- m_Color
- When you write classes in Visual C try and
follow this convention too it makes code a lot
easier to read.
42Hungarian Notation
- Hungarian notation is a naming convention
- This stems from C, because of the lack of type
checking. The notation isnt essential, but again
keep it consistent and code is a lot more clear.
b a logical variable (bool) c an
individual character (char) fn a function h
a handle, used to identify something (usually
an int value) i an integer p a pointer s
a string
43MFC Program Construction
- Visual C has a thing called AppWizard which can
produce a Windows Program without us writing a
single line of code. - But, we dont have to use it we can set up a
program ourselves from scratch. - The simplest program that you can write is a
window with no text displayed in it useless but
sufficient to Show the Fundamentals
44Lets Write an MFC program
- Create a new project workspace File New
- Choose Win32 Application, and then empty project.
- With this minimal choice we need to ensure that
the linker knows we want to use MFC classes. If
we dont, well end up with obscure linker
errors. - Use Project Settings go to the general tab
and make sure that the Microsoft Foundation
Classes option is showing Use MFC in a Shared DLL.
45Using those MFC classes
- Now create a new source file and insert it into
the project. Were going to put all of our code
into this one file. - First step is to actually include the MFC classes
they are stored in the afxwin library so just
use - include ltafxwin.hgt
- To produce a complete program well only need to
derive 2 classes from MFC an application class
and a window class.
46the Application class
- The class CWinApp is fundamental to any MFC
windows program. - An object of the CWinApp class includes
everything necessary for - starting
- initialising
- running
- closing the application
- The first thing we need to do is to derive our
own application class from CWinApp. We will be
defining a specialised version of the class to
suit our needs.
47the Application class
- A catch handler resembles a function definition
- class CJimsApp public CWinApp
- public
- virtual BOOL InitInstance()
-
This is just normal public inheritance
CWinApp is a key Microsoft Foundation Class.
CJimsApp is derived from it.
We are going to override the virtual function
InitInstance thats where well put code to
display our window.
48the Window class
- We need a window as an interface to the user in
MFC this is referred to as the Frame Window. -
- class CJimsWnd public CFrameWnd
- public
- CourWnd() Create(0, Dumb MFC
application -
Again we derive our own windows class
Our base class will be the MFC frame window class
- CFramWnd
Create function is inherited it will create the
window and attach it to our COurWnd object.
49Completing the program
- Now all we need to do is rewrite that virtual
function - BOOL CJimsAppInitInstance()
-
- m_pMainWnd new CJimsWnd
- m_pMainWnd-gtShowWindow(m_nCmdShow)
- return TRUE
-
Construct a window on the free store
inherited integer, indicating how the window
should be shown
CJimsWnd has inherited a function to actually
display the window
50The Finished Code
- include ltafxwin.hgt
- class CJimsApp public CWinApp
- public virtual BOOL InitInstance()
-
- BOOL CJimsAppInitInstance()
- m_pMainWnd new CJimsWnd
- m_pMainWnd-gtShowWindow(m_nCmdShow)
-
- class COurWnd public CFrameWnd
- public CourWnd() Create(0, Dumb MFC
application -
- CJimsApp AnApplication
Define an Application Object
51The Finished Product
- Press F7 to compile and Ctrl-F5 to execute the
program. - We can resize the window, move it around,
minimise, maximise, close iteverything you would
expect.
52The Document Concept
- If you use Visual C and MFC you accept a
specific structure - you accept that your data is
stored and processed in a particular way. - The structure of MFC forces on us two more
concepts that we havent considered yet - a document class
- a view class
- A document is the name given to a collection of
data in your application with which a user
interacts.
53Documents can be Anything
- A document isnt limited to text it could be..
- data for a game
- a geometric model
- a text file
- a collection of data on Gladiators, the famous
nineties action/game show. Contenders, ready.. - A document is an object of Cdocument in the MFC.
- As before we can create an inherited version,
adding our own data members and methods.
54So What is a view?
- A view always relates to a particular document
object it provides a mechanism for displaying
some or all of the data stored in a document. - To use a view, you define your own class from the
MFC class CView. - A view object and the window object are
completely distinct. - A view is actually displayed in its own window
that exactly fills the client area of a frame
window.
55View-Window Relationship
The document contains all the application data
but a view may only show part of the data
but a view may only show part of the data
Client area of the window
Document
56Linking a Documents views
- A document object automatically maintains a list
of pointers to its associated views. - A view object had a data member pointing to the
document it relates too. - Each frame window stores a pointer to the
currently active view object. - But how on earth are all these things
coordinated? Gosh darn it, by another class A
document Template.
57Document Templates
- Manages the document objects in your program.
- Also manages the windows and views associated
with the document. - You have one document template for each different
type of document that you have in your program. - Remember we derive our own document from the base
class. We use this when we set up the document
template using the ltCJimsDocumentgt syntax.
58Document Templates
Application Object
Document Template
Pointer to
Pointer to
Document Object
Frame Window
Pointer to
Pointer to
Creates
View Object
Pointer to
59The Application and MFC
- MFC covers a lot of ground and involves a lot of
classes. - Taken together these classes are a complete
framework for an application. - So the MFC is very abstract in form you must
derive your own versions. - Whatever tool you use to code your Windows
Programs will have its own classes. The Visual
C ones arent particularly great but very
popular nonetheless.
60The MFC Hierarchy
Cobject
CCmdTarget
CDocTemplate
CDocument
CwinThread
CWnd
CFrameWnd
CWinApp
CView
CSingleDocTemplate
CJimsWnd
CJimsApp
CJimsView
CJimsDoc
Jims Application
61Messages
- Windows communicates with your program by sending
messages to it. - Old-fashioned coding required you to setup your
own winproc() to handle these messages. - If you use MFC it takes out all the drudgery for
you, and you dont even need to code a winproc(). - MFC provides you with functions to handle the
individual messages you are interested, and
allows you to ignore the rest.
62Message Maps
- The association between a Windows message and a
function in your program is established by a
Message Map. - This is simply a table of member functions for
that class that handles windows messages. - Each entry in the message map connects a
particular type of message to a function Visual
C automatically adds them via appWizard. - The point is if you use visual C and you
understand these concepts you will be
incredibly more efficient.