Professional Documents
Culture Documents
1. #include <iostream>
2.
3. int main()
4. {
5. std::cout << "Hello World!";
6. return 0;
7. }
In this simple program we notice some elements listed. The line numbers are
used for reference only and are not part of the program code.
Also notice that the line ends with a semi-colon. C++ statements are terminated with
semi-colons.
Line 6: The return statement is used to end a function or method when a value
is expected to be sent back to a caller. In this case, the caller is the operating
system and the value returned is an integer value of 0. If the program reaches
this statement, returning a value of 0 is an indication to the operating system
that the code executed successfully. In the past, programmers would return 0 to
indicate successful execution and non-zero values to indicate that an error had
occurred in the program somewhere.
Line 7: This line closes out the body of the function main() and is necessary so
the compiler knows where the function or method ends, but is also used for
other purposes that will be covered later in the course on variable scope and
visibility.
Type Name Bytes Alias Range
wchar_t, char16_t, and 2 or 4 __wchar_t 0 to 65,535 (wchar_t & char16_t), 0 to 4,294,967,295 (char32_t)
char32_t
making use of short rather than int if your data range permits
using a double rather than a float to get greater a accuracy for values
representing money
using a wchar_t for character data that doesn't fit in the standard ASCII
character set, such as Japanese kanji
Introducing Variables
Bookmark this page
Variables are identifiers that you create to hold values or references to objects
in your code. A variable is essentially a named memory location.
When you create a variable in C++, you must give it a data type. You can
assign a value to the variable at the time you create it or later in your program
code. This is known as initializing the variable. Even though you can initialize a
variable separate from its creation, you must assign the data type when you
define the variable. C++ will not allow you to use an uninitialized variable to help
prevent unwanted data from being used in your application. The following code
sample demonstrates declaring a variable and assigning a value to it. C++
supports two methods of initializing a variable.
int myVar = 0;
int yourVar{1};
C++ has some restrictions around identifiers that you need to be aware of.
Identifiers can only contain letters (in any case), digits, and the underscore
character. You can only start an identifier with a letter or an underscore
character. You cannot start the identifier with a digit. myVar and _myVar are
legal but 2Vars is not.
C++ has a set of reserved keywords that the language uses. You cannot use
these keywords as an identifier in your code. You may choose to take
advantage of the case-sensitivity of C++ and use Long as an identifier to
distinguish it from the reserved keyword long, but that is not a recommended
approach.
To keep up to date on the reserved keywords for C++ you should always refer
to the C++ standard but the current standard lists reserved keywords in the C++
Standard document found here.
Introducing Constants
When you declare a constant in C++, you must assign a literal value to that
constant at the same time. You cannot assign it later in program nor can you
change the value in code later. Also, because the value cannot be changed,
you cannot initialize a constant with a variable or any other value that will have
its value modified during runtime.
Type Conversions
Casting refers to converting one data type to another. Some data conversions
are not possible while some are possible but result in data loss. C++ can
perform many conversions automatically, what is known as implicit casting or
implicit conversion. For example, attempting to convert a smaller data type to
larger data type as shown here:
In the first line, we declare an integer data type and assign it a value of 12. The
next line declares a long data type and in the third line, we assign the integer
data type value to the long data type. C++ automatically converts the data type
for you. This is known as a widening conversion. Some programmers also call
this an expanding assignment. We are expanding or widening the data type to a
larger one. In this case, there is no loss in data. The following table highlights
some potential data conversion problems.
This table only deals with numeric data type conversions. There are other
conversion types such as from character to numeric or numeric to character, or
among character types. C++ also uses the boolean type that represents true or
false. If you assign a zero value to a bool variable, it will be converted to false.
Any non-zero value is converted to true.
When you want to explicitly perform a conversion or cast, you can use the type
cast features of C++. For example, the previous widening conversion in the int
to long cast was implicit but you can also tell the compiler that you are know
what you are doing by using the type cast statement as in:
C++ also provides a cast operator that is more restrictive in its usage. This in
the form static_cast (type). This static cast operator can be used for
converting numeric values or to numeric values. As an example:
char ch;
int i = 65;
float f = 2.5;
double dbl;
So far you have been introduced to the intrinsic data types that C++ supports.
These are types that contain the data literals directly. The int type directly stores
the literal integer value, for example.
C++ also provides support for complex data types. These are also referred to as
compound data types. Mostly because they store more than one piece of data
or potentially more than one data type.
An array is a set of objects that are grouped together and managed as a unit.
You can think of an array as a sequence of elements, all of which are the same
type. You can build simple arrays that have one dimension (a list), two
dimensions (a table), three dimensions (a cube), and so on. Arrays in C++ have
the following features:
When you declare an array, you specify the type of data that it contains and a
name for the array. To declare a single-dimensional array, you specify the type
of elements in the array and use brackets, [] to indicate that a variable is an
array. The following code example shows how to create a single-dimensional
array of integers with elements zero through nine.
int arrayName[10];
You can also choose to create an array and initialize it with values at the same
time as in the following example that declares and integer array and assigns
values to it. The compiler knows how large to make the array by the number of
values in the curly braces:
You can also declare an array and only initialize some of the elements:
In this case, we have declared an array of size 10 but have only assigned
values to the first three elements. The compiler will initialize the remaining
elements to the default value for the data type the array holds. In this case, int
data type, the remaining values are initialized to 0.
You can access data in an array in several ways, such as by specifying the
index of a specific element that you require or by iterating through the entire
array and returning each element in sequence.
The following code example uses an index to access the element at index two.
Note: Arrays are zero-indexed, so the first element in any dimension in an array
is at index zero. The last element in a dimension is at index N-1, where N is the
size of the dimension. If you are using some other languages, such as C#, and
you attempt to access an element outside this range, the C# runtime will throw
an exception (error). C++ doesn't offer such protection. If you attempt to access
an element that is outside the bounds of your array, you will still return data, but
you have no idea what that data is.
You can also iterate through an array by using a for loop. You will cover loops in
module 3 so don't worry if you don't completely understand this example at this
time. Essentially, the for loop starts at 0 and repeats the portion in the curly
braces {} for each of the five steps in the loop.
The following code example shows how to use a for loop to iterate through an
array.
Strings
Strings are a series of characters. C++ represents strings in one of two ways.
The first maintains backward compatibility with the C language and represents
the string as a character array. There is one aspect to a C-style string that is
important to note. The last character of every string you store is the null
character string, typically represented by the ASCII code for 0 which is \0. This
is necessary so that the compiler knows when the string ends. An example
demonstrates a C-style string stored in a character array:
The most common mistake made by users of the C-style string is to forget to
make the char array large enough to accommodate the \0 character, but also
forgetting include the \0. In the previous example, a programmer might think
that an array of size 5 would be large enough to contain Hello because that's
how many characters are in the word. However, the null character would not be
included in the second array, which could result in errors in code that uses this
array. The reason is that C++ does not consider the isNotAString array to be a
string.
Consider the output displayed in Figure 2.1. Note that the first output correctly
terminates because C++ encountered the null (\0) character. The second did
not terminate and output the contents of adjacent memory.
In the previous example, the first line creates an array of size 6 and assigns the
string literal Hello to the array. The second example lets the compiler infer the
size from the string literal itself. Note that neither of these two string literals
specifies a \0 character. The compiler will implicitly add that for you. However,
caution is advised in the first line to ensure that you allow enough room in the
array size specified for the null character. If you create an array that is larger
than required for the string literal along with the null character, then C++ simply
fills the remaining elements of the array with null characters.
The string Class If the use of character arrays, single quoted characters, and
null termination characters are making you think that strings aren't worth the
hassle, consider the string class instead. The ISO/ANSI standard helped to
expand the string handling capabilities of C++ by adding the string class.
In order to use the string class, you have to include the string header file. We
have not covered namespaces yet but to make typing much easier, you would
add a using statement as in the following example.
Without the using directive, you would have to type std::string every time
you wanted to use the string class in your code, as in the second line above.
As you can see from the code example, you use string in the same manner in
which you would use any other data type in C++. You also do not need to add a
null character to terminate your string.
Structures
Arrays can store multiple pieces of data in one compound data type but recall,
the data types must all be of the same type. If that is the case, how might you
store multiple pieces of data in one type, where the individual pieces are of
different data types? For example, let's say that we want to store information
about a coffee bean. We might want to store information about the bean type,
its strength, and perhaps which country it originated from. In this case, we could
use all strings to store that information but what if the strength was intended to
be a number from 1 to 10. In this case, we would want to store two strings and
one integer in our coffee bean data type.
We haven't covered classes yet, which is another data type we could use, but
instead, we will use a structure (struct) to store this information. Structures are
known as user-defined types. You define the struct by giving it a name and then
adding the member data types as in the following example:
struct coffeeBean
{
string name;
string country;
int strength;
};
Recall that in order to use the string data type in our struct, the C++ file that
contains the struct must include the string header file. This code snippet also
assumes that using namespace std; has also been included.
Once we have defined the structure, we can then use it in our code the same as
any other data type. To use the coffeeBean struct in your code, you simply
declare a new variable of that type as shown in this example.
struct coffeeBean
{
string name;
string country;
int strength;
};
You can assign values to a struct using one of the methods seen here. For
myBean, we assign values in the curly braces while for newBean, we use the
dot notation. You can also access the values of the the struct members using
the dot notation as well, shown in the cout statement at the end.
Unions
union numericUnion
{
int intValue;
long longValue;
double doubleValue;
};
numericUnion myUnion;
myUnion.intValue = 3;
cout << myUnion.intValue << endl;
myUnion.doubleValue = 4.5;
cout << myUnion.doubleValue << endl;
cout << myUnion.intValue; cout << endl;
Why use a union over a struct if it can only hold one piece of data at a time?
Consider a situation where you are programming an application that will run on
a device with limited memory. You would like to use a data type that can
support multiple types internally like a struct, but not necessarily all at the same
time. For example, part numbers for components in manufacturing where the
part number may be a number or perhaps a string, depending on the
manufacturer of the part. In this case, you could use the union to represent a
numeric and a string data type internally but only assign the proper data type
based on the part number.
Enumerations
In the topics on variables and constants, it was noted that anytime you want to
create a value for use in a program, where the value should never change, you
used a constant. An enumeration can be considered a way to create what are
known as symbolic constants. The most common example is to use an enum to
define the day of the week. There are only seven possible values for days of the
week, and you can be reasonably certain that these values will never change.
To create an enum, you declare it in your code file with the following syntax,
which demonstrates creating an enum called Day, that contains the days of the
week:
Sunday = 0
Monday = 1
Tuesday = 2
etc.
You can change the default by specifying a starting value for your enum as in
the following example.
In this example, Sunday is given the value 1 instead of the default 0. Now
Monday is 2, Tuesday is 3, etc.
The keyword enum is used to specify the "type" that the variable Day will be. In
this case, an enumeration type. Consider the following code sample:
The first line defines the enumeration Day and assigns seven values to the
enum. Sunday is listed as the first day of the week and is initialized with the
value one.
C++ Operators
Because you will start to learn about control statements in C++, it's important to
understand the C++ operators that exist in the language first, as they play an
important role in control statements.
You will work with comparison operators to determine if values are equal,
greater, or less than each other. C++ also allows you to use mathematical
operators for incrementing values to help control the number of iterations in a
loop. You can also make use of bitwise operators to speed up some operations
in your code.
if Statements
if Statements
Note the use of curly braces in the code sample. You can eliminate the curly
braces if your statement to execute is a single line statement. C++ understands
that if no curly braces are used, the line immediately after
the if(condition) will be executed if the condition is true. Otherwise that
line of code is not executed and the code resumes after that line. If you need to
have multiple statements execute if the condition is true, then you must use
curly braces to surround the body of the if structure as in the code sample.
TIP: To avoid confusion as to which lines will execute for a true condition, a
recommended practice is to always use curly braces for your if statement.
if else Statements
string response;
if (response == "connection_failed")
{
// Block of code executes if the value of the response
variable is "connection_failed".
}
else
{
// Block of code executes if the value of the response
variable is not "connection_failed".
}
if statements can also have associated else if clauses. The clauses are
tested in the order that they appear in the code after the ifstatement. If any of
the clauses returns true, the block of code associated with that statement is
executed and control leaves the block of code associated with the
entire if construct.
The following code example shows how to use an if statement with an else
if clause.
else if Statements
string response;
if (response == "connection_failed")
{
// Block of code executes if the value of the response
variable is "connection_failed".
}
else if (response == "connection_error")
{
// Block of code executes if the value of the response
variable is "connection_error".
}
else
{
// Block of code executes if the value of the response
variable is neither above responses.
}
You can create as many else if blocks as necessary for your logic, or until
you become completely lost from too many else if clauses. If you require
any more than five else if clauses, you might want to consider
the switch statement, presented next.
switch Statements
If there are too many else if statements, code can become messy and
difficult to follow. In this scenario, a better solution is to use a switchstatement.
The switch statement simply replaces multiple else if statements. The
following sample shows how you can use a switchstatement to replace a
collection of else if clauses.
switch Statement
Notice that there is a block labeled default:. This block of code will execute
when none of the other blocks match. The default block is optional.
In each case statement, notice the break keyword. This causes control to
jump to the end of the switch after processing the block of code. If you omit
the break keyword, the application may not perform as you anticipate. In other
languages, such as C#, omitting the break; keyword will cause the code to no
longer compile.
Without the break statement, the code will "fall through" to the remaining cases
until it encounters a break statement. Be very careful in using fall through logic
in your switch statements. The most common use for a fall through scenario is
when you want to handle multiple cases with a single statement or set of
statements.
enumerations
In this example, we have two integer variables, i and j which are initialized to 1
and 2 respectively. The ternary operator is embedded inside the cout statement
and essentially follows this pattern:
In the code example here, j is greater than i so the condition evaluates to false
and the value for j (2), is output to the console along with the text is greater. In
other words, the output is "2 is greater." If i was 5 and j was 2, the output would
be, "5 is greater."
The for loop executes a block of code repeatedly until the specified expression
evaluates to false. You can define a for loop as follows.
The following code example shows how to use a for loop to execute a code
block 10 times.
for Loop
for (int i = 0 ; i < 10; i++)
{
// Code to execute.
}
In this example, i = 0; is the initializer, i < 10; is the condition, and i++ is
the iterator.
while Loops
A while loop enables you to execute a block of code while a given condition
is true. For example, you can use a while loop to process user input until the
user indicates that they have no more data to enter. The loop can continue to
prompt the user until they decide to end the interaction by entering a sentinel
value. The sentinel value is responsible for ending the loop.
while Loop
string response;
cout << "Enter menu choice " << endl << "More" << endl <<
"Quit" << endl;
cin >> response;
It's imperative to include the prompt again, inside the loop braces. Failure
to put this into the loop body will result in an infinite loop because the
sentinel value can never be changed.
do Loops
You might want to use a do loop if you know that the code will only execute in
response to a user prompt for data. In this scenario, you know that the
application will need to process at least one piece of data, and can therefore
use a do loop.
do Loop
string response;
do
{
cout << "Enter menu choice " << endl << "More" << endl
<< "Quit" << endl;
cin >> response;
A couple of aspects to note about this loop. First of all, the response
variable is declared outside of the loop. This is important due to
scope resolution requirements. If you declare the variable inside the
loop, then the while(response != "Quit") portion will not "see" the
response variable.
Second, note that in comparison with the while loop, the prompt only
needs to be placed inside the loop body and is not required ahead of
the loop. This is possible because the do loop executes the contents
of the loop at least once due to the condition check being at the end
of the loop.
Third, notice the semicolon at the end of the loop. This is required in
the do loop and not in the while or for loop.
Nesting Loops
Nesting of loops is possible in C++. The most common is to nest for loops. An
example of nesting a for loop might be used for games, such as dealing four
hands to card players from a deck of 52. Your outer loop would count from 0 to
51 for the total number of cards in the deck and the inner loop would count from
0 to 3 to represent the 4 hands being dealt. Of course, if you aren't dealing the
entire 52 cards, you can change the outer loop counter to represent that fact.
The following code example shows nesting for loops to output a chess or
checkerboard representation using the characters X and O.
}
else
{
cout << "O ";
cout << "X ";
}
}
alternate = !alternate;
You create a function by defining it. The function definition may contain a return
type, a function name, parameters to accept incoming arguments, and finally a
body which contains the code that will execute as part of that
function. Functions may or may not return a value back to the caller and they
may or may not accept arguments passed in to the function.
When you move into more advanced C++ programming, you can also overload
functions. This refers to the practice of using the same function name to refer to
multiple functions that perform different actions. Why would you do
this? Consider a simple scenario where you want to perform addition on some
values so you create a function called Sum(). You could overload Sum() by
creating variants such as:
The compiler will know which function to call, based on the number of
arguments passed in.
Function Prototypes
When declaring a function, you specify its storage class, return type, name, and
parameters. Some refer to this as the function signature. In C++ it is also
called a function prototype.
In C++, function prototypes belong in header files. Recall that the header file is
what gets imported into other source code files so that the compiler can track
proper use of functions and other aspects of the included files. The function
prototype only contains the function's signature with no implementation
details. The implementation details along with the function signature, define the
function. The function definition exists in the source code file (.cpp).
Function Parameters
A function can accept values that will be used in the statements in the function
body. These values are known as arguments when passed to a function. The
arguments are passed into parameters. Parameters are the placeholders that
are found inside the parentheses of a function declaration, as shown in the
following example where a and b are the parameters. Note that the data types
for these are specified and that the parameters are separated by a comma.
When calling the function, you use the function name, followed by an
open parenthesis, the arguments that will be passed into the
parameters, and then a closing parenthesis, as shown here:
Note that you don't have to include the data type specifiers for the
arguments being passed in but you must know the data type the
function expects. This is one of the reasons for declaring a function
prototype prior to using it in code.
Inline Functions
One of the goals for using functions in your code is to create discrete pieces of
functionality in your code that is easier to test and maintain. However, functions
also have an impact on application performance. The reason for this impact
results from the operations that must be performed when a function is
called. For example, registers in the CPU need to be reset, stack pointers are
created, memory is consumed for these pointers and the values that are passed
into and out of the function. For simple functions that may perform only a
single operation or have only a single, simple statement, you might wonder why
creating a function for it is worth the effort.
You can still make use of a function to perform the necessary computation but it
makes more sense to create the function as an inline function. Inline functions
avoid the overhead associated with traditional function calls. You create an
inline function by prefixing it with the inline keyword. A common function found
in applications for a sorting algorithm such as bubble sort, is a swap
function. Swap takes two variables and swaps their values as shown here:
if you are using inline functions and change the function in anyway,
the code needs to be recompiled because the code for that function
will need to be updated in each location it was used.
use inline functions only for small functions that are used frequently,
not for large functions.
MSDN defines storage class as, "A storage class in the context of C++ variable
declarations is a type specifier that governs the lifetime, linkage, and memory
location of objects."
Lifetime refers to how long the variable "hangs around" in memory from the
point at which it is declared and the point at which it is destroyed (the memory it
used is released). For the most part, once a variable goes out of scope, its
memory will be released back to the operating system for reuse.
Linkage refers to the visibility of a variable outside of the file that contains it.
The heap, or free store, is a pool of memory that is used to store objects that
dynamically allocated at run time by your application. An object is what you will
learn about in the next topic on object-oriented programming. You create and
destroy objects on the heap by using specific instructions in your program code.
1. #include <iostream>
2. int main()
3. {
4. int total = 0;
5. for(int i = 1; i <= 10; i++)
6. {
7. total += i;
8. }
9. std::cout << "The sum of the numbers 1 to 10 is " <<
total << std::endl;
10. std::cout << "Current value of i is " << i <<
std::cout;
11. return 0;
12. }
In the previous code, the variable total is declared inside main() but
outside of the for loop. This means that total is visible (in scope) for
the entire main() method, which also includes inside the for
loop. However, the variable i is declared inside the for loop's
initialization section and is therefore constrained to the scope of the
for loop. The code at line 10 will result in an error in C++ that
indicates the variable is undefined. Anyplace other than inside the
for loop is out of scope for the variable i.
static - identifiers declared with static are allocated when the program
starts and deallocated when the program execution ends. Declaring a
variable as static in a function means that the variable will retain its
value between calls to the function.
extern - used to declare an object that is defined in another
translation unit of within the enclosing scope but has an external
linkage.
Introduction
Classes enable you to create your own custom, self-contained, and reusable
types. A class file is often considered a blueprint for objects that you use in your
code. Typically you will create class files to help model real-world objects in
your code.
An example of this might be the software that manages a bank ATM. The
software would need to understand the concept of customers, accounts,
transactions, etc. It's far easier to implement the software application by
modelling these real world objects as software objects (classes) in your code.
In this module, you will gain an introduction to classes in C++ that will cover the
basics only. The second installment of the C++ course will delve deeper into
object oriented concepts in C++.
Creating Classes
In C++, a class is a programming construct that you can use to define your own
custom types. When you create a class, you are effectively creating a blueprint
for the type. The class defines the behaviors and characteristics, or class
members, which are shared by all instances of the class. You represent these
behaviors and characteristics by defining methods and fields within your class.
//Declaring a Class
class Rectangle
{
public:
int _width;
int _height;
};
Here we have declared a class called Rectangle and given it two public member
variables called _width and _height, that will be used to represent the width and
height of our rectangle. Note that they are accessible directly because they are
public, as a result of the public: modifier.
Using a Class
Now that we have a class created to represent a rectangle, we can use that in
our code to create instances of a rectangle in our program. When we create a
new rectangle from this class, it is known as a rectangle object and will be given
a unique name. That way ,we can refer to it in our program directly and
distinguish it from other rectangle instances that we might create, should our
program require more than one.
void main()
{
Rectangle outer;
Rectangle inner;
outer._width = 10;
outer._height = 10;
inner._width = 5;
inner._height = 5;
}
In this sample code, we have created two rectangle objects called outer and
inner. Then, using what is known as "dot notation" or the dot operator, we
provide values for the width and height of each rectangle. The outer rectangle
is 10 x 10 and the inner rectangle is 5x5.
Class Initialization
C++ offers a couple of options for initializing your classes. You can initialize the
member variables by using the dot operator and setting the values explicitly or
you can include a constructor in your class that is responsible for initialization
the member variables. You'll see this in the demo video next as well as more
information in the topic on encapsulation.
Introducing Encapsulation
Recall that the keyword const was used to indicate that a data type you use in
your code is a constant and cannot have its value changed during application
runtime. Objects in your code can also make use of the const keyword to
indicate that the objects are immutable. Immutable simply means that they
cannot change.
In the next couple of video segments, you will be introduced to const objects
and see a demo of how to use them in code.