Read an Excerpt
[Figures are not included in this sample chapter]
Sams Teach Yourself Visual C++ in 24 Hours
- 3 -
Functions, Structures, and Classes
In the first two hours you've learned some of the basic concepts behind C++, and
you have written some simple programs. In this hour you will be introduced to some
more advanced Visual C++ programming topics. In particular, you will learn
- How to use expressions and statements in C++ programs
- How to use functions to provide small reusable chunks of code
- How to use structures and classes to create source code and data components
You will also build sample programs that illustrate the topics you learn in this
What Are Statements and Expressions?
Statements and expressions are the elements defined by the C++ language that are
converted into machine code by the compiler to build your C++ programs. Seems like
a textbook-type definition, doesn't it? In reality, though, defining exactly what
they are is difficult. When talking about a building, we can say that it is made
of bricks, boards, and other things; we can define the brick or board very easily.
In the case of the C++ programming language, it is much more difficult; here we are
dealing with abstract concepts. The difference between a statement and expression
is very subtle, as you will soon see. Although it appears to be confusing at first,
the language will become understandable with practice. Eventually the C++ language
will become as natural to you as your native language.
Just like the simple Hello programs, all C++ programs are made up of statements
and expressions. Expressions and statements range from the simple statements that
were shown in the Hello programs to very complex expressions that stretch across
All statements end with semicolons. In fact, the simplest statement is called
the null statement, and it consists of only a single semicolon, as follows:
The null statement isn't used often; it's used only in situations in which the
C++ syntax requires a statement, but no real work needs to be done.
You use a statement to tell the compiler to perform some type of specific action.
For example, you know from the console mode programs you created that the following
statement will display the characters Hello World! on your screen:
cout << "Hello World!" << endl;
A declaration is another type of statement. A declaration introduces a variable
to the compiler. The following line is an example of a simple declaration:
This tells the compiler that myAge is an integer.
An assignment expression is used to assign a value to a variable, using the assignment
operator, =, as follows:
myAge = 135;
Every expression has a value. The value of an assignment expression is the value
of the assignment. This means that the following statement assigns the value 42
to the variables yourAge and myAge:
myAge = yourAge = 42;
The program in Listing 3.1 demonstrates how to assign a value to a variable.
LISTING 3.1. A C++ PROGRAM THAT ASSIGNS A VALUE TO A VARIABLE.
using namespace std;
myAge = 42;
cout << "Hello" << endl;
cout << "My age is " << myAge << endl;
The assignment operator is just one example of the operators available in C++.
More operators are discussed in the next section.
The C++ language contains operators that you can use to write addition, subtraction,
multiplication, and other expressions. Some common math operators are shown in Table
TABLE 3.1. SOME COMMON MATH OPERATORS USED IN C++.
All math operators group from left to right. The multiplication and division operators
have a higher precedence than the addition and subtraction operators. This means
that the following expressions are equivalent: a + 5 * 3 a + 15 You can use parentheses
to force an expression to be evaluated in a preferred order. Note the grouping of
the following expression: (a + 5) * 3 This expression adds 5 to the value stored
in a and then multiplies that value by 3. The math operators can also be combined
with an assignment operator, as follows:
myAge = 40 + 2;
The expression 40 + 2 has a value of 42. After that value is
calculated, the value of the expression is stored in the myAge variable.
NEW TERM: A function is a group of computer instructions that performs
a well-defined task inside a computer program. Functions are one of the primary building
blocks of C and C++ applications. Functions provide a way to break up a large program
into more manageable parts. At the same time, functions make it possible to perform
the same task at various points within the program without repeating the code.
For example, if you buy a wagon you'll find that it comes with a full set of assembly
instructions and has four identical wheels. Why should the instructions repeat the
steps to assemble a wheel four times? It is much easier to describe the wheel assembly
process once and indicate that you perform the process for each wheel. The wheel
assembly instructions are a module (function) within the full set of assembly instructions
(program) that is executed four times.
Every C++ program has at least one function; this function is usually called main.
The main function is called by the operating system when your application
starts; when main has finished executing, your program has finished.
Most Windows programs written in C++ have a similar function named WinMain
that serves the same purpose as main in a console-mode program. In an MFC
program the WinMain function is part of the MFC library code--you will rarely
need to provide a WinMain function yourself.
Before you can use a function, you must declare it by supplying a function prototype
to the compiler. To declare a function you specify the function's name, its return
value, and a list of any parameters that are passed to it, as shown here:
int CalculateAge(int nYearBorn);
This line is a function prototype for the CalculateAge function, which
takes a single integer as a parameter and returns an integer as its result. A function
that returns no value is declared as returning the void type.
NEW TERM: The traditional way to provide function prototypes is to place
them in header files, which are usually named with an .h extension.
Header files that are part of the C++ standard library do not use the .h
extension; two examples of standard header files are iostream and math.
These header files contain all the prototypes and other declarations needed for IO
streams and math functions to be compiled correctly.
A function is defined the same way the main function is defined. All
function definitions follow the same pattern; it's basically the function prototype
with the function's body added to it. The function definition always consists of
- The function's return value
- The function's name
- The function's parameter list
- The actual function body, enclosed in curly braces
Listing 3.2 shows how to use a function to display the Hello World! message. To
run this project, create a new console-mode project named HelloFunc, using
the steps described for the Hello and Hello2 projects in the first two hours.
LISTING 3.2. THE HELLO WORLD! PROGRAM REWRITTEN TO USE A FUNCTION.
using namespace std;
// Function prototype
void DisplayAge(int nAge);
void DisplayAge(int nAge)
cout << "Hello World! I'm " << nAge << " years old." << endl;
Because the function doesn't return a value to the calling function, the return
type is defined as void.
In the C++ language, the act of transferring control to a function is known as
calling the function. When a function is called, you supply a function name
and a list of parameters, if any. The following steps take place when a function
- 1. The compiler makes a note of the location from which the function was
called and makes a copy of the parameter list, if any.
2. Any storage required for the function to execute is temporarily created.
3. The called function starts executing, using copies of the data that was
supplied in the parameter list.
4. After the function has finished executing, control is returned to the
calling function and memory used by the function is released.These steps are shown
in Figure 3.1, which uses the function from Listing 3.1 as an example.
FIGURE 3.1. Steps involved in calling a function.
NOTE: The requirement that you declare functions before using them is an extension
of the C++ type system. Because function prototypes are required, the compiler can
detect errors such as incorrect parameters used in a function call.
What Are Structures?
NEW TERM: A structure is a data type that contains other data types
grouped together into a single user-defined type.
NOTE: Structures are commonly used when it makes sense to associate two or
more data variables.
An example of a structure is a payroll record, where the number of hours worked
and the pay rate are combined in a structure, as shown in Figure 3.2.
FIGURE 3.2. Structures are made up of member variables.
Declaring a structure introduces a new type of variable into your program. Variables
of this new type can be defined just like int, char, or float
variables are defined. Listing 3.3 is an example of how a structure is typically
LISTING 3.3. USING A STRUCTURE TO CALCULATE A WEEKLY SALARY.
using namespace std;
payrollRecord.dHours = 40.0;
payrollRecord.dRate = 3.75;
cout << "This week's payroll information:" << endl;
cout << "Hours worked : " << payrollRecord.dHours << endl;
cout << "Rate :$" << payrollRecord.dRate << endl;
double dSalary = payrollRecord.dRate * payrollRecord.dHours;
cout << "Salary :$" << dSalary << endl;
What Are Classes?
NEW TERM: A class allows data and functions to be bundled together
and used as if they were a single element. Classes typically model real-world concepts
that have both data and some sort of behavior, although this is not a hard and fast
NEW TERM: A function that is defined as part of a class is often called
Classes are similar to structures; in fact, classes really are just structures
with a different name. Classes have one feature that makes them very useful for object-oriented
programming: Unless a member of a class is specifically declared as public,
that member is generally not accessible from outside the class. This means that you
can hide the implementation of methods behind the external interface.
NOTE: Like functions, classes are an important part of the C++ programming
language. In fact, one of the earliest names for C++ was C with Classes.
NEW TERM: An instance of a class, sometimes called an object, is
an occurrence of a class. An instance of one of your classes can be used or manipulated
inside your programs.
When using Visual C++, objects such as dialog boxes, window frames, menus, and
buttons are controlled by C++ classes. A class is just a description of the object
that can be created and the actions that can be performed on it.
A C++ class has two main parts:
- The class declaration. This contains the class interface and information
about data members for the class. The class interface usually is located in a header
file having a .H suffix. Any file in your program that uses the class must
use the #include directive so that the preprocessor adds the class declaration
to the source file.
- The class implementation. This includes all the member functions that
have been declared as part of the class. The class implementation usually is located
in a file that has a .CPP suffix.
The data that makes up an object, and the functions that are performed on that
object, are combined to form a class, or a description of that object. Classes can
inherit functionality from other objects, and you easily can add new classes that
leverage existing classes.
Classes and instances of classes are not the same things. This can sometimes be
a confusing concept if you are new to C++ or object-oriented programming. Think of
a class as the description of an object; an instance of a class is a concrete occurrence
of that class.
NEW TERM: A constructor is a special member function that is created
when an object of the class is created. A constructor always has the same name as
the class and never has a return value, not even void. The purpose of the
constructor is to place a newly created object into a known state. Typically, constructors
can allocate system resources, clear or set variables, or perform some other type
NEW TERM: A destructor is a special member function that is called
as an object is destroyed. The destructor is declared as having no return type and
is never declared with a parameter list. The name of the destructor is the class
name prefixed by a tilde (~) character.
Defining a destructor is not necessary unless specific tasks must be performed
to clean up after an object, such as releasing system resources that might have been
As an example of a C++ class, let's look at a class that represents a weekly payroll
record. The class must have two member variables:
- The number of hours worked
- The hourly salary
The class will also define three member functions that
- Set the hourly salary
- Set the number of hours worked
- Retrieve the calculated salary for the pay period
The definition of a class is similar to that of a structure, except that the keyword
class is used instead of struct. Listing 3.4 provides a declaration
for a CWeeklyPayRecord class.
LISTING 3.4. A DECLARATION FOR A WEEKLY PAY RECORD CLASS.
void HoursWorked( double dHours );
void PayRate( double dRate );
The keywords public and private are used to grant or deny access
to members of the class. Any members of the class declared after the public
keyword can be accessed from outside the class, just as though they were members
of a structure. Any members of the class declared after the private keyword
are not accessible outside the class. Any number of public or private
access specifiers can be present in a class declaration. The closest access specifier,
reading from top to bottom, is the one that is currently controlling a declaration.
Listing 3.5 is a complete example that uses the CWeeklyPayRecord class,
with some typical member functions added.
LISTING 3.5. A COMPLETE EXAMPLE USING THE CWeeklyPayRecord
using namespace std;
void HoursWorked( double dHours );
void PayRate( double dRate );
// main - Create a weekly salary object, and calculate this
// week's salary.
weeklyPay.HoursWorked( 40.0 );
weeklyPay.PayRate( 3.75 );
cout << "This week's payroll information:" << endl;
cout << "Salary :$" << weeklyPay.GetSalary() << endl;
// Member functions for the CWeeklyPayRecord class
void CWeeklyPayRecord::HoursWorked( double dHours )
m_dHours = dHours;
void CWeeklyPayRecord::PayRate( double dRate )
m_dRate = dRate;
return m_dHours * m_dRate;
Note that the member functions in Listing 3.5 are prefixed with CWeeklyPayRecord::
when they are defined. The names of all member functions are prefixed with their
class names; this is the only way the compiler can determine to which class the function
belongs. The only exception to this rule is a function that is defined inside the
Rectangles and Regions
The rectangle is a fundamental component of most Windows programs. Because most
windows and controls are rectangular, it isn't surprising that one of the most commonly
used data structures in Windows programming is used to represent a rectangle.
Rectangles are often used to represent the position or size of all types of windows:
main windows as well as controls, toolbars, and dialog boxes. There are two basic
types of rectangle coordinates:
- Screen rectangle coordinates, which place a rectangle in relationship to the
- Client rectangle coordinates, which always have their top and left values set
to zero and provide the size of a rectangle that represents a window's client area
Screen rectangle coordinates are often used when moving a window in relation to
the entire screen. Client rectangles are most commonly used when positioning controls
or drawing inside a control or other window.
When requesting the dimensions of a rectangle, you must pass a CRect
variable to one of the Windows rectangle functions. The following two lines of code
declare an instance of CRect as a variable and pass it to the GetClientRect
The next example uses a client area rectangle to display a message to the user,
just like the HelloMFC program in the first hour. The new example will draw the message
in the center of the client area; if the window is resized, the message will be redrawn
in the center of the new rectangle.
Create an MFC AppWizard application named HelloRect, following the steps presented
in the first hour. Modify the OnDraw function found in the CHelloRectView
class so that it looks like the function shown in Listing 3.6.
LISTING 3.6. USING A RECTANGLE TO CENTER A MESSAGE IN A WINDOW.
void CHelloRectView::OnDraw(CDC* pDC)
pDC->DrawText("Hello Client Rectangle!", -1, rcClient,
DT_SINGLELINE | DT_CENTER | DT_VCENTER );
Build the HelloRect application and run it from Developer Studio. Note that if
you resize the window, the message is redrawn so that it remains in the center of
the client area.
In this hour you learned some of the more advanced building blocks that make up
C++ programs: functions, structures, and classes. As an example of how C++ classes
are used, a payroll class was created and used. The hour finished with a discussion
about rectangles and regions in Windows programs.
- Q What is the difference between a rectangle that uses screen coordinates
and a rectangle that uses client coordinates?
A Every window in a Windows application can be represented by a rectangle;
this rectangle will typically use either screen or client coordinates. The rectangle
that results from these coordinates is always the same, the difference is only in
the point of reference that is used to measure the rectangle.
Q Can a structure have member functions?
A Absolutely. A class and a structure are exactly the same, except that all
members of a structure are accessible by default, while class members are private
(not accessible) by default. You will learn more about access restrictions in the
Q Why is no function prototype required for main()?
A The short answer: because the C++ standard says you don't need one. The
purpose of function prototypes is to introduce new functions to the compiler; because
every C++ program is required to have a main function, no function is necessary.
The Workshop is designed to help you anticipate possible questions, review what
you've learned, and begin thinking ahead to putting your knowledge into practice.
The answers to the quiz are in Appendix A, "Quiz Answers."
- 1. What is a function?
2. What are the four parts of a function definition?
3. How are classes different from structures?
4. What function is called when an instance of a class is created?
5. What function is called when an instance of a class is destroyed?
6. What is the value of the expression a = 42?
7. What symbol is used for multiplication?
8. What symbol is used for division?
- 1. Write a console-mode program that asks for a distance in miles and
converts the distance into feet. There are 5,280 feet in a mile.
2. Modify the HelloRect program to display different messages in different
parts of the main window.
3. Modify the CWeeklyPayRecord class so that it calculates overtime
4. Create a declaration for a class that tracks a screen location. The class
should store an X and Y coordinate position and include member functions that set
and retrieve the coordinates.