Professional Documents
Culture Documents
Programming
With C++
Lecture 1
Mr. James Chambua
12/02/10 1
Course Outline
Number of Credit :
3 credits
Objective:
To extend the student’s knowledge of Object Oriented
Programming (OOPVisual Basic) in comparison with relation
to other (OOP) languages
Understand the Visual C++ eventdriven programming
concepts, terminology, and available tools
To Learn the fundamentals of designing, implementing, and
distributing a wide variety of Visual C++
12/02/10 2
Contents:
Introduction to Visual Programming.
The Visual C++ Development Environment
C++ Review
Using Controls in Your Application
Allowing User Interaction
Creating Menus and dialogs for Your
Application
Creating Single and Multiple Document
Interface Applications
Saving and Restoring WorkFile Access
Manipulating Data from an ODBC Database
12/02/10 3
On completion of this course a student should:
Have a knowledge and understanding of issues involved in Visual
programming.
Be able to design and program an application using Visual C++.
Text Book
Friedman, F.L. and Koffman, E.B., (2000). Problem Solving,
Abstraction, and Design Using C++. USA, AddisonWesley
Delivery: Lecture 30 hours; Lab Practical 15 hours
Assessment: Coursework 40%; Examination 60%
12/02/10 4
Introduction to Visual
Programming
Before we begin our course, let us understand some basic
concepts of programming.
According to Webopedia, a computer program is an
organized list of instructions that, when executed, causes the
computer to behave in a predetermined manner. Without
programs, computers are useless.
We need to use certain computer language to communicate
with the computer. There are many computer languages out
there, some of the examples are Visual Basic, Fortran,
Cobol, Java, C++, Turbo Pascal, Assembly language and
etc.
12/02/10 5
Introduction to Visual
Programming
Microsoft Visual C++ (often abbreviated as MSVC) is a
commercial integrated development environment (IDE)
product engineered by Microsoft for the C, C++, and C++/CLI
programming languages.
It has tools for developing and debugging C++ code,
especially code written for the Microsoft Windows API, the
DirectX API, and the Microsoft .NET Framework.
Before Visual C++ was developed we had Microsoft C and
Microsoft C++.
12/02/10 6
Introduction to Visual
Programming
With Visual C++, you can program practically everything
depending on your objective. For example, you can
program educational software to teach science ,
mathematics, language, history , geography and so on.
You can also program financial and accounting software
to make you a more efficient accountant or financial
controller.
For those of you who like games, you can program that
as well. Indeed, there is no limit to what you can
program! There are many such program in the internet,
so you must spend more time on the internet in order to
benefit the most with this language.
12/02/10 7
Introduction to Visual
Programming
VISUAL C++ is a VISUAL and events driven
Programming Language. These are the main divergence
from the C/C++. In C/C++, programming is done in a
textonly environment and the program is executed
sequentially. In VISUAL C++, programming is done in a
graphical environment.
In the C/C++, you have to write program codes for each
graphical object you wish to display it on screen,
including its position and its color. However, In Visual C+
+ , you just need to drag and drop any graphical object
anywhere on the form, and you can change its color any
time using the properties windows.
12/02/10 8
Introduction to Visual
Programming
On the other hand, because users may click on
a certain object randomly, so each object has to
be programmed independently to be able to
response to those actions (events).
Therefore, a VISUAL C++ Program is made up
of many subprograms, each has its own program
codes, and each can be executed independently
and at the same time each can be linked
together in one way or another.
12/02/10 9
The Visual C++ Development
Environment
To run Visual C++ programs one needs to have install
Visual C++ development environment in the computer.
After installing Visual C++ development environment in
your computer, start the Developer Studio (the Microsoft
Visual development environment), you will see a window
that looks like Figure 1.1 below. Each of the areas has a
specific purpose in the Developer Studio environment.
You can rearrange these areas to customize the
Developer Studio environment so that it suits your
particular development needs.
12/02/10 10
The Visual C++ Development
Environment
Solution
Explorer Editor Area
Output Area
12/02/10 11
The Visual C++ Development
Environment
The Output Pane might not be visible when you start
Visual C++ for the first time. After you compile your first
application, it appears at the bottom of the Developer
Studio environment and remains open until you choose
to close it. The Output pane is where Developer Studio
provides any information that it needs to give you; where
you see all the compiler progress statements, warnings,
and error messages; and where the Visual C++ debugger
displays all the variables with their current values as you
step through your code. After you close the Output pane,
it reopens itself when Visual C++ has any message that it
needs to display for you.
12/02/10 12
The Visual C++ Development
Environment
The Editor Area is the area on the right side of the
Developer Studio environment is the editor area. This is
the area where you perform all your editing when using
Visual C++, where the code editor windows display
when you edit C++ source code, and where the window
painter displays when you design a dialog box. The
editor area is even where the icon painter displays when
you design the icons for use in your applications. The
editor area is basically the entire Developer Studio area
that is not otherwise occupied by panes, menus, or
toolbars.
12/02/10 13
The Visual C++ Development
Environment
Menu Bars
The first time you run Visual C++, three toolbars display
just below the menu bar( Standard toolbar, WizardBar
toolbar, Build minibar ). Many other toolbars are
available in Visual C++, and you can customize and
create your own toolbars to accommodate how you best
work.
The Standard toolbar contains most of the standard tools
for opening and saving files, cutting, copying, pasting,
and a variety of other commands that you are likely to
find useful.
12/02/10 14
C++
Review
12/02/10 15
Creating Your C++
Application
Using Visual C++
Our first example is a simple program that displays "Hello World" on
the screen. For this, you create a workspace and the C++ file
required for the program. The procedure for writing a C++ program
using Visual C++ is simple and easy. Follow these steps:
On the File menu, point to New, and then click Project
From the Visual C++ project types, click Win32, and then click
Win32 Console Application.
Enter a project name Hello.
In the Win32 Application Wizard, select Empty Project and
click Finish.
12/02/10 16
Creating Your C++
Application
Using Visual C++
Visual C++ creates the workspace of your application. Visual C++
actually creates a directory Hello, which enables you to store all files
related to a particular project in one area. You will begin adding the
files you require for this project:
If Solution Explorer is not visible, click Solution Explorer on the
View menu.
Add a new source file to the project:
Rightclick on the Source Files folder in Solution Explorer, point
to Add, and click New Item.
Click C++ File (.cpp) from the Code node, enter a file name
Helloworld, and then click Add.
12/02/10 17
Creating Your C++
Application
Using Visual C++
The Helloworld.cpp file is where you add the C++ source
code. All C++ source code files have a .cpp extension.
Later, we will cover other file types.
We will create all other examples in this section in a
similar way. The only difference is that the names of the
workspaces and the files are different.
Helloworld.cpp
The Helloworld program displays HELLO WORLD on the
screen. Below slide contains the code. Type the code
exactly as shown. C++ is case sensitive, so main is not
the same as MAIN, which is not the same as Main.
12/02/10 18
Hellworld.cpp
// Workspace Name: Hello
// Program Name: Helloworld.cpp
# include <iostream>
int main()
{
Std::cout<< "HELLO WORLD \n";
return 0;
}
12/02/10 19
To run the program, follow these steps:
1. Select File | Save to save your work.
2. On the Build menu, click Build Solution.
Visual C++ compiles and links the program to create an executable file. The
Output window displays information about the compilation progress, such as the
location of the build log and a message that indicates the build status.
Also it indicates the success or failure of the compilation. A successful compilation
returns
Hello.exe 0 error(s), 0 warning(s)
If you encounter any errors, verify that all the lines of the program were typed
exactly as shown.
To execute the Helloworld program, On the Debug menu, click Start without
Debugging .
12/02/10 20
Functions and
Variables
The Helloworld program consists of only one function, main(). A functional
C++ program typically consists of more than a single function. To use a
function, you must first declare it.
A function declaration is also called its prototype. A prototype is a concise
representation of the entire function. When you prototype a function, you
are actually writing a statement, and as mentioned before, all statements in
C++ should end with semicolons. A function prototype consists of a return
type, name, and parameter list. The return type in the main() function is int,
the name is main, and the parameter list is (), null.
A function must have a prototype and a definition. The prototype and the
definition of a function must agree in terms of return type, name, and
parameter list. The only difference is that the prototype is a statement and
must end with a semicolon. The codes below illustrates this point with a
simple program to calculate the area of a triangle.
12/02/10 21
Area.cpp
// Workspace: Triangle
// Program name: Area.cpp
// The area of a triangle is half its base times height
// Area of triangle = (Base length of triangle * Height of triangle)/2
#include <iostream> // Precompiled header
using namespace std;
double base,height,area; // Declaring the variables
double Area(double,double); // Function Prototype/declaration
int main() {
cout << "Enter Height of Triangle: "; // Enter a number
cin >> height; // Store the input in variable
cout << "Enter Base of Triangle: "; // Enter a number
cin >> base; // Store the input in variable
area = Area(base,height); // Store the result from the Area Âfunction
// in the variable area
cout << "The Area of the Triangle is: "<< area << endl ; // Output the Âarea
return 0;
}
double Area (double base, double height) // Function definition
{
area = (0.5*base*height);
return area;
}
12/02/10 22
VARIABLE DATA
TYPES.
12/02/10 23
The if Statement,
Operators, and
Polymorphism
While programming large complex programs, it is often necessary to
query the user and provide direction to the program based on his
input. This is accomplished by using the if statement. The format of
the if statement is
if (this expression) do this;
The if statement is often used in conjunction with relational operators.
Another format of the if statement is
if (this expression) do this; else do this;
Because if statements often use relational operators, let's review
relational operators.
Relational operators are used to determine if two expressions or
numbers are equal. If the two expressions or numbers are not equal,
the statement will evaluate to either 0 or false. Tables below lists the
six relational operators and the three logical operators defined in C++.
12/02/10 24
The if Statement, Operators,
and Polymorphism
RELATIONAL OPERATORS. LOGICAL OPERATORS
12/02/10 25
Overload.ccp
// Workspace Name: Overload
// Program Name: Overload.cpp
# include <iostream>
using namespace std;
double base,height,radius; // Global variables
double Area_of_triangle,Area_of_circle; // Global variables
int choice; // Global variable
double Area (double,double); // Function prototype
double Area (double); // Function prototype
const double pi = 3.14; // Constant variable
void main() // main function
{
cout << "To find the area of a Triangle, input 1 \n";
cout << "To find the area of a Circle, input 2 \n";
cin >> choice;
if (choice == 1) {
cout << "Enter the base of the triangle: ";
cin >> base;
cout << "Enter the height of the triangle: ";
cin >> height;
Area_of_triangle = Area(base,height);
cout << "The Area of the Triangle is: "<<Area_of_triangle<<endl;
}
if (choice == 2) {
cout << "Enter radius of the Circle: ";
cin >> radius;
Area_of_circle = Area(radius);
cout << "The area of the Circle is: "<<Area_of_circle<<endl;
}
if (choice != 1 && choice != 2) {
cout << "Sorry! You must enter either 1 or 2 \n";
}
}
double Area (double base, double height) {
return (0.5*base*height);
}
double Area(double radius) {
return (pi*radius*radius);
}
12/02/10 26
Starting Your First
Project
After reviewing your C++ programming its time for your first
Visual C++ application, we are going to create a simple
application that presents the user with two buttons (see figure
below).
The first button will present the user with a simple greeting
message, and the second button will close the application. In
building this application, you will need to do the following
things:
1. Create a new project workspace.
2. Use the Application Wizard to create the application framework.
12/02/10 27
Starting Your First
Project
3. Rearrange the dialog that is automatically created by the
Application Wizard to resemble how you want the application to
look.
4. Add the C++ code to show the greeting to the user.
5. Create a new icon for the application.
12/02/10 28
Starting Your First
Project
12/02/10 29
Starting Your First
Project
Creating the Project Workspace:
Every application development project needs its own project workspace
in Visual C++. The workspace includes the directories where the
application source code is kept, as well as the directories where the
various build configuration files are located. You can create a new
project workspace by following these steps:
Select File | New | Project. This opens the New Project Wizard
On the Projects type, select MFC.
Make sure on the templates to select MFC Applications.
Type a name for your project, such as Project1, in the Project Name
field.
Click OK. This causes the New Wizard to do two things: create a project
directory (specified in the Location field) and then start the AppWizard.
12/02/10 30
Starting Your First
Project
Using the Application Wizard to Create the Application
Shell
The AppWizard asks you a series of questions about what
type of application you are building and what features and
functionality you need. It uses this information to create a shell
of an application that you can immediately compile and run.
This shell provides you with the basic infrastructure that you
need to build your application around. You will see how this
works as you follow these steps:
In Step 1 of the AppWizard, specify that you want to create a
Dialogbased application. Click Next at the bottom of the
wizard.
12/02/10 31
Starting Your First
Project
In Step 2 of the AppWizard, the wizard asks you about a number of
features that you can include in your application. You can check the
option which you want your application to include for example, your
application should have minimized and maximized box etc.
In the field near the bottom of the wizard, delete the project name
(Project 1) and type in the title that you want to appear in the title bar of
the main application window, such as My First Visual C++
Application. Click Next at the bottom of the wizard.
In Step 3 of the AppWizard, leave the defaults for including source file
comments and using the MFC library as a DLL. But uncheck the option
for including support for ActiveX controls if you will not be using
any ActiveX controls in your application. Because you won't be
using any ActiveX controls in today's application, go ahead and
uncheck this box. Click Next at the bottom of the wizard to proceed to
the final AppWizard step.
12/02/10 32
Starting Your First
Project
The final step of the AppWizard shows you the C++ classes that
the AppWizard will create for your application. Click Finish to let
AppWizard generate your application shell.
Before AppWizard creates your application shell, it presents you
with a list of what it is going to put into the application shell,
based on the options you selected when going through the
AppWizard. Click OK and AppWizard generates your
application.
After the AppWizard generates your application shell, you are
returned to the Developer Studio environment. You will notice
that the workspace pane now presents you with a tree view of
the classes in your application shell. You might also be
presented with the main dialog window in the editor area of the
Developer Studio area.
12/02/10 33
Starting Your First
Project
Select Build | Build solution to compile your application.
As the Visual C++ compiler builds your application, you see
progress and other compiler messages scroll by in the Output
pane. After your application is built, the Output pane should
display a message telling you that there were no errors or
warnings.
Select Debug | Start without Debugging to run your application.
Your application presents a dialog with a TODO message and
OK and Cancel buttons. You can click either button to close the
application.
12/02/10 34
Designing Your
Application Window
Now that you have a running application shell, you need to
turn your focus to the window layout of your application. Even
though the main dialog window may already be available for
painting in the editor area, you should still navigate to find the
dialog window in the workspace so that you can easily find the
window in subsequent development efforts. To redesign the
layout of your application dialog, follow these steps:
Select the Resource View tab in the workspace pane
Expand the resources tree to display the available dialogs. At this
point, you can doubleclick the IDD_PROJECT1_DIALOG dialog
to open the window in the Developer Studio editor area.
Select the text displayed in the dialog and delete it using the
Delete key.
12/02/10 35
Designing Your
Application Window
Select the Cancel button, drag it down to the bottom of the dialog,
and resize it so that it is the full width of the layout area of the
window,.
Rightclick the mouse over the Cancel button, opening the pop
up menu. Select Properties from the menu, and the properties
dialog opens.
Change the value in the Caption field to &Close. Close the
properties dialog by clicking the Close icon in the upperright
corner of the dialog.
Move and resize the OK button to around the middle of the
window.
12/02/10 36
Designing Your
Application Window
On the OK button properties dialog, change the ID value to
IDHELLO and the caption to &Hello.
Now when you compile and run your application, it will look
like what you've just designed.
12/02/10 37
Adding Code to Your
Application
You can attach code to your dialog through the Visual C++
Class Wizard. You can use the Class Wizard to build the
table of Windows messages that the application might
receive, including the functions they should be passed to for
processing, that the MFC macros use for attaching
functionality to window controls. You can attach the
functionality for this first application by following these steps:
To attach some functionality to the Hello button, rightclick
over the button and select Add Event Handler from the
popup menu.
If you had the Hello button selected when you opened the
Event Handler Wizard, it is already selected in the
command name.
12/02/10 38
Adding Code to Your
Application
With IDHELLO selected, select BN_CLICKED in the list of
messages types and click Add Edit button. This will create the
function and add it to the message map.
After the function is added for the click message on the Hello
button, select the OnHello function in the list of available function.
Click the Edit Code button so that your cursor is positioned in the
source code for the function, right at the position where you
should add your functionality.
Add the following code, just below the TODO comment line.
MessageBox(_T("Hello Welcome to Visual C+
+."), _T("Project3"),
MB_ICONEXCLAMATION | MB_OKCANCEL);
When you compile and run your application, the Hello button should
display the message.
12/02/10 39
Finishing Touches
Now that your application is functionally
complete, you can still add a few details to finish
off the project. Those finishing touches include
Creating the dialog box icon
Adding maximize and minimize buttons
12/02/10 40
Creating the Dialog
Box Icon
If you noticed the icon in the topleft corner of your application
window, you saw three blocks with the letters M, F, and C.
What does MFC have to do with your application? MFC
stands for Microsoft Foundation Classes. Technically, it's the
C++ class library that your application is built with, but do you
want to broadcast that to every user who sees your
application? Most likely not. You need to edit the application
icon to display an image that you do want to represent your
application.
In the tree view of your application resources in the
workspace pane, expand the icon branch and select the
IDR_MAINFRAME icon. This brings the application icon into
the editor area of the Developer Studio.
12/02/10 41
Creating the Dialog
Box Icon
Using the painting tools provided, repaint the icon to display
an image that you want to use to represent your application
When you compile and run your application, you will notice
your custom icon in the topleft corner of your application
window. Click the icon and select About Hello from the drop
down menu.
On the About dialog that Visual C++ created for you, you can
see a large version of your custom icon in all its glory.
12/02/10 42
Adding Maximize and
Minimize Buttons
In the dialog editor, where you design your application window,
you can add the minimize and maximize buttons to the title bar
of your application window by following these steps:
1. Select the dialog window itself as if you were going to resize
the window.
2. Using the popup menu (from rightclicking the mouse), select
the dialog properties.
3. Select the Appearance tab.
After you select true on the minimize and maximize boxes, you
can compile and run your application. The minimize and
maximize buttons appear on the title bar.
12/02/10 43
Summary
Today you got your first taste of building applications
using Visual C++. You learned about the different areas
of the Visual C++ Developer Studio and what function
each of these areas serves. You also learned how you
can rearrange the Developer Studio environment to suit
the way you work. You also learned how you can use
the Visual C++ wizards to create an application shell and
then attach functionality to the visual components that
you place on your application windows.
12/02/10 44
Exercise
Add a second button to the About window in
your application. Have the button display a
different message from the one on the first
window.
12/02/10 45