Lesson Number

Overview of Managed C++

 

Introduction to Instructions

 

Introduction to C++

C++ is a language used to create a group of instructions given to a computer to perform a specific task. These instructions are put together in a group commonly called a computer program, also called a program, also called a computer application, also called an application. In this e-book, these four expression will be used to refer to the same thing.

A person who writes instructions in C++ is called a programmer. A person who executes these instructions is called a user.

C++ was created a few years ago, based on another language called C, to solve many of the problems that programmers encountered. At the same time, it was made a (very) powerful language. As it usually happens, C++ solved many problems but also presented its own issues, including some limitations or difficulties. C++ is still widely used and is probably the most popular language in the computer world as it is present on most operating systems. To reduce many of the problems encountered in C++, Microsoft created an enhanced version of C++. This language is sometimes called Managed Extensions For C++. We will find out why the word Managed. As for Extensions, one of this new language's goals is to "extend" the capabilities of C++ beyond the current functionality of C++. This language is also sometimes called Managed C++. In this e-book, we will call it Managed C++ to make sure we don't confuse it with (traditional) C++.

From now on, in this e-book, when we state the word "C++", we refer to a feature or characteristics that is present on both C++ and Managed C++. When we use the expression "Managed C++", we are referring to an issue that is available only in Managed C++.

At the time of this writing, only Microsoft provides an environment that supports the Managed C++ language. Therefore, in this e-book, we will study the Managed C++ language using (only) Microsoft Visual C++ .Net, which is also part of Microsoft Visual Studio .Net. This e-book assumes that you have either Microsoft Visual C++ .Net or Microsoft Visual Studio .Net installed on the computer you will use to follow our instructions and do the exercises. At the time of this writing, we are using the 2003 version.

A console application is one that displays its result(s) in a (black) DOS window:

All of the programs in this e-book will be created as console applications. There are various ways you can create a console application in Visual C++ .Net. You can create a regular C++ console application. You can create a Managed C++ console application. Or you can create a .Net empty application and then make it a console application.

 

Practical Learning: Introducing C++

  1. To start, open your programming environment by clicking Start -> (All) Programs -> Microsoft Visual Studio .Net 2003 -> Microsoft Visual Studio .Net 2003
  2. To start a console application, on the Start Page, click New Project
  3. In the Project Types section, click Visual C++ Projects
  4. In the Templates section, click Empty Project (.NET)
  5. In the Location, type a folder that would hold the current exercise. An example would be
    C:\Programs\MSVC .Net 2003
  6. In the Name box, type Console1 or another name for the new project:
     
  7. Click OK

 

C++ Instructions

Computer programming mostly consists of giving instructions to a computer. The instructions are written in a normal file also called a source file. It has the .cpp extension.

To lay a valuable foundation of these instructions, some primary instructions ship with Managed C++ so that you can start by "plugging" these early instructions into your programs. These fundamental instructions are provides in files called libraries. To "plug" one of these instructions, type the # preprocessor operator, followed by the include word, followed by the name of the file between < and >.

One of the files that holds some instructions is called iostream. You can make it part of your program with:

#include <iostream>

The main Instruction

A C++ program has a main entry point. That's the first part checked when you execute a program. This entry point is created as follows:

int main()
{
	return 0;
}

When we learn about functions, we will find out what the return 0; line means.

 

Practical Learning: Introducing C++

  1. To create a source file, on the main menu, click Project -> Add New Item
  2. In the Templates section, click C++ File (.cpp)
  3. In the Name box, type Exercise
     
  4. Click Open
  5. To use what we have done so far, change the file as follows:
     
    #include <iostream>
    
    int main()
    {
    	return 0;
    }

 

Introduction to the Compiler

The program you create is written in plain text, as you may have realized by now. Unfortunately, the computer can't read and doesn't understand it. In order to make your program usable, it must be "translated" in a language the computer understands. To do this, Visual C++ .Net is equipped with an internal program (or a suite of programs) called the compiler. Although the process of making a program ready can be tedious, at this stage of our learning, we will simply consider that, when you think that your program is ready, you can call the compiler to analyze, validate, and execute it. This is simply done by either pressing Ctrl + F5 or clicking Debug -> Start Without Debugging from the main menu. Whenever you execute a program in Visual C++, the compiler would ask you to first save it.

When executing the program, the compiler "scans" it for errors. If it finds at least one that is not acceptable, it would stop and point you to the error. If it finds everything fine or acceptable, it would display the result on the screen.

Console applications in Visual C++ are configured to display a friendly message when they have finished. All you have to do is press any key such as Enter to end.

Practical Learning: Executing a Program

  1. To test the application, on main menu, click Debug -> Start Without Debugging
  2. To close the DOS window, press Enter

 

Namespaces

 

Introduction

A namespace is a normal name that identifies an entity or a group of instructions. The name could be anything such as somebody's name, the name of the company's department, or a city, etc. To create a namespace, you start with the namespace keyword followed by the name of the section. The name follows some rules you must follow.

In this e-book, any name we will use must:

  • Start with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice
  • Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _Score_Side1
  • Cannot include special characters such as !, %, ], or $
  • Cannot include an empty space
  • Cannot be any of the words used internally used by Managed C++. Such words are referred to as reserved; they are also called keywords
  • Should not be longer than 32 characters (although allowed)

A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth.

C++ is case-sensitive. This means that WORD, Word, and word are three completely different words. To make your programming experience easier and personal, you can add your own rules to those above. In this e-book, most names will:

  • Start in uppercase; in some situations, a name will start with an underscore, when needed. Examples are Country, Printer, _Number
  • Start each element of its combined words in uppercase. Examples are FirstName, DateOfBirth. Sometimes the first part will start in lowercase, such as firstName or dateOfBirth

Reserved Words

The Managed C++ language has a list of words reserved for its own use and you must not use any of these words to name your own objects. The words you should not use to name things are:
Managed C++ Reserved Words
asm
bool
auto
catch
class
const_cast
break
case
char
const
continue
default
delete
do
double
dynamic_cast
else
enum
explicit
extern
false
float
for
friend
goto
if
inline
int
interrupt
long
mutable
namespace
new
register
return
short
operator
private
protected
public
register
reinterpret_cast
signed
sizeof
static
static_cast
string
String
struct
switch
template
this
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while

Avoid starting the names of your objects with two underscores. The Managed C++ language has many reserved words that start like that and sometimes, when you execute a program, it would usually think that a name that starts with __ is one of its keywords. The reserved words in this context are:

 
Additional Managed C++ Reserved Words
__abstract
__box
__delegate
__event
__finally
__gc
__identifier
__interface
__nogc
__pin
__property
__sealed
__try_cast
__typeof
__value
__wchar_t

Here are additional words you should avoid to name anything:

Other Reserved Words
__export
__fastcall
__huge
__import
__int16
__int32
__int64
__int8
__interrupt
__loads 
__near
__pascal
__rtti
__seg
__stdcall
__thread
__try
_stdcall
pascal

 

Creating a Namespace

The section that is part of a namespace starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Here is an example:

namespace School { }

Since a namespace can be made of numerous parts, one line could become (too) crowded. Therefore, each curly bracket should be displayed on its own line:

namespace School
{
}

The section between the curly brackets can be called the body of the namespace. Between the curly brackets, you can type anything that is part of the namespace. Every expression, or almost everyone of them, must end with a semicolon. As we will see in various examples in this e-book, this rule that applies to expressions doesn't mean a line, since an expression can spread in more than one line, and various expressions can be written on the same line. Just remember that, to end an expression, type a semicolon.

Here is an example:

namespace School
{
Grades; Teachers; Students;
}

A part that is included in a namespace is also called a member of the namespace. For the same reason of crowdedness mentioned above, each member should be typed on its own line:

namespace School
{
Grades;
Teachers;
Students;
}

Indentation consists of "pushing" each line in the body by a certain number of characters to the right. This makes the code easier to read. The default number of characters is 4 and is usually automatically done for you. Otherwise, here are the members of the namespace indented:

namespace School
{
	Grades;
	Teachers;
	Students;
}

It is important to note that the way we defined this namespace is for illustration purposes. This is not exactly how the members of a namespace are created.

 

Accessing Members of a Namespace

After creating the necessary parts of a namespace, to access one of its parts, you can use the :: operator. To do this, in the desired location where you want to use a part of the namespace, type the name of the namespace, followed by the :: operator, followed by the desired member of the namespace. Here is an example:

namespace School
{
	Grades;
	Teachers;
	Students;
}

School::Teachers;

The std Namespace

As mentioned earlier, C++ ships with various already made instructions you can use to complete your program. The language also provides its own namespaces that include various objects (we will later call classes) you can use in your programs. One of the namespaces provided by C++ is called std. The iostream library we mentioned earlier is just one part of the std namespace. The following libraries are part of the std namespace:

algorithm iomanip list ostream streambuf
bitset ios locale queue string
complex iosfwd map set typeinfo
deque iostream memory sstream utility
exception istream new stack valarray
fstream iterator numeric stdexcept vector
functional limits      

The following additional libraries can be used to include C header files into a C++ program:

cassert cios646 csetjmp cstdio ctime
cctype climits csignal cstdlib cwchar
cerrno clocale cstdarg cstring cwctype
cfloat cmath cstddef    

One of the objects that are part of the std namespace is called cout. The cout instruction is used to display something on the DOS window. To use it, the simplest way is to type it, followed by the << operator, followed by what you want to display.

 

Practical Learning: Using a Namespace

  1. To use the std namespace and to display a number on the console, change the program as follows:
     
    #include <iostream>
    
    int main()
    {
    	std::cout << 12;
    	return 0;
    }
  2. Execute the program

The Using Keyword

We saw that, to access something that is part of a namespace, you must "qualify" that object using the :: operator. There is a shortcut to this approach. If a namespace has already been created, before accessing one of its parts, you can use a special keyword. This is done with the using keyword. To do this, type using followed by the name of the namespace, before accessing the desired part.

With the using keyword, you can include as many external namespaces as necessary.

 

Practical Learning: Using the Keyword

  1. To use the using keyword, change the program as follows:
     
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	cout << 12;
    	return 0;
    }
  2. Test the program
 
 

Introduction to Objects

 

Overview

An object is an entity made of various or different parts. These parts are what constitute the (nature of) the object. They also describe the object. An example of an object is a house. It is made of four or more walls, a roof, one or more bedrooms, one or more doors, probably one or more windows, etc. This list also allows us to easily recognize a house because as soon as we see these parts put together, we consider the object to be a house:

In C++, an object is called a class. The concept of an object is also referred to as a structure because, like our example, a house is mainly a structural entity.

To create a simple class, you can start with a word struct followed by a name for the class or structure. You must follow the same rules we mentioned to name an object. 

Typing the struct keyword followed by a name indicates that you want to create a class. If you are not ready to define that class, that is, if you are not ready to "describe" what the class can be used for, you can end with a simple semicolon. Here is an example:

struct House;

Such a class is allowed but at this time, it would not do anything. It is as if you had created a class called Thing without showing what can be done with it:

struct Thing;

This type of expression allows you to define the object later on. To define a class, its parts are created as a list that starts with an opening curly bracket "{" and ends with a closing curly bracket "}", like a namespace. Unlike a namespace, since a class is created as an expression, its body must end with a semi-colon. Based on this, our House class can be created as follows:

struct House { };

Notice that the semicolon is typed after the closing curly bracket because that's where the expression ends.

Like a namespace, a class can be made of numerous parts, such as walls, roof, bedroom, doors, listed as sub-objects of a class, one line could become (too) crowded. Therefore, each curly bracket should be displayed on its own line:

struct House
{
};

The section between the curly brackets can be called the body of the class. In the body of the class, you can list its parts. Like the namespace, the items that are part of a class are also called its members. Here is an example:

struct House
{
Walls; Doors; Roof; TypeOfFloor;
};

For the same reason of crowdedness mentioned above, each member should be typed on its own line:

struct House
{
Walls;
Doors;
Roof;
TypeOfFloor;
};

As done for the namespace, the members of a class can be indented to make them easier to read:

struct House
{
	Walls;
	Doors;
	Roof;
	TypeOfFloor;
};

Once again, the way we defined the House class is for illustration purposes. This is not how the members of a class are defined.

Author Note Because of (maybe) a (bad) habit some of us picked up from Microsoft Foundation Classes (MFC) library, all of the classes (including structures) in our lessons will have names that start with C. Also, the names of enumerators in this book will imitate some convention from the Visual Component Library (VCL) (omitting the T). In both cases, there is absolutely no secret, no reason, and no improvement to that: it is simply a habit that we have become used to. Trying to justify it will come only down to personal opinion and preference.
 

A Class in a Namespace

Imagine a city like Baltimore. It has many houses and each house has an address. The addresses of these houses follow some rules that apply only to their location. For example, an house could have an address like 1804 Lockhart Ave. It is not unlikely that you would find this exact same address for a house in another city like Boston. For this reason, a house must also be identified as belonging to a particular city. This is the idea behind namespaces.

A class can be created in a namespace. In fact, the cout object we used earlier is a class created in the std namespace.  In our example, a namespace can be used to identify a city. To create a class inside of a namespace, simply add it based on what we know so far. Here is an example:

namespace Baltimore
{
	struct CHouse
	{
		Address;
		Walls;
		Doors;
		Roof;
		TypeOfFloor;
	};
}

To access a class that is part of a namespace, in the desired location, type the name of the namespace, followed by the :: operator, followed by the name of the class. Here is an example:

namespace Baltimore
{
	struct CHouse
	{
		Address;
		Walls;
		Doors;
		Roof;
		TypeOfFloor;
	};
}

Baltimore::CHouse;
 

The System Namespace

What makes Managed C++ an Extension of C++ is that it adds many of the functionalities that are not available in C++. In other words, Managed C++ extends the functionality of C++. One of the features brought is a new or different way to display things on the screen. In fact, Managed C++ uses a new approach. Instead of using a class such as cout, Managed C++ uses functions. An issue we will learn in other lessons. To support this functionality, Managed C++ adds a new namespace called System. Inside of the System namespace is a class called Console that is used to display things on the console screen.

The Console class contains assignments (called functions) to display information on the screen or to retrieve information from the user who types it in the DOS window. The function that is used to display text on the screen is called Write. To use the Write() function, inside of its parentheses, type the item you want to display. An example would be a natural number:

System::Console::Write(0);

Besides the Write() function, the Console class also provides a function called WriteLine(). The difference is that, after displaying something on the screen, the Write() function keeps the caret on the same line but the WriteLine() transfers the caret to the next line. We will see various examples of this behavior in this e-book.

Like C++, Managed C++ ships with various instructions in libraries. Unlike C++, the Managed C++ libraries come in other types files. Such a file is called a dynamic link library or DLL. Such a library usually has the extension .dll. The DLL that contains the System namespace is called mscorlib. To use it, in the file that will need it, type

#using <mscorlib.dll>

 

Practical Learning: Using the Keyword

  1. To use the System namespace, change the program as follows:
     
    #include <iostream>
    #using <mscorlib.dll>
    
    int main()
    {
    	System::Console::WriteLine(254);
    	std::cout << 12;
    	return 0;
    }
  2. Test the application and return to MSVC
  3. As done with the std namespace, to use the using keyword, change the program as follows:
     
    #include <iostream>
    #using <mscorlib.dll>
    
    using namespace System;
    
    int main()
    {
    	Console::WriteLine(254);
    	std::cout << 12;
    	return 0;
    }
  4. Test the application and return to MSVC
  5. To access two external namespaces using the using keyword, change the program as follows:
     
    #include <iostream>
    #using <mscorlib.dll>
    
    using namespace std;
    using namespace System;
    
    int main()
    {
    	Console::WriteLine(254);
    	cout << 12;
    	return 0;
    }
  6. Test the application. This would produce:
     
    254
    12Press any key to continue
  7. Close the console window and return to MSVC

The Microsoft .Net Framework Library

One of the strengths of Managed C++ is that it is part of a (very) broad environment or library called the Microsoft .Net Framework. This is a library of objects used to create various types of objects using different languages. For example, it allows you to create classes and/or namespaces to make available to languages other C++. In the same way, you can use classes created in other languages in your Managed C++ programs.

 

Details on Namespaces and Classes

 

A Namespace With Various Classes

It is perfectly possible to create as many classes as you judge necessary in a class. Here is an example of a Baltimore namespace that contains three classes:

namespace Baltimore
{
	struct CHouse
	{
		Address;
		Walls;
		Doors;
		Roof;
		TypeOfFloor;
	};

	struct CCityStatistics
	{
		Area;
		Population;
	};

	struct TypeOfCommunication
	{
	};
}

To access a class that is part of a namespace, type the name of the namespace, followed by the :: operator, followed by the name of the class.

Namespace Nesting

A namespace can be created inside of another namespace. Creating a namespace inside of an existing namespace is referred to as nesting. The namespace inside of another namespace is nested.

To create a namespace inside of another, simply type it as you would create another namespace. Here is an example:

namespace Baltimore
{
	namespace Residences
	{
	}

	struct CFamilyHouse
	{
	};
	struct CCityStatistics
	{
	};

	struct CTypeOfCommunication
	{
	};
}

In the example above, the Residences namespace is nested inside of the Baltimore namespace. After creating the needed namespaces, nested or not, you can create the necessary classes inside of the desired namespace.

To access anything that is included in a nested namespace, you use the :: operator before calling a member of a namespace or before calling the next nested namespace. Here is an example:

namespace Baltimore
{
	namespace Residences
	{
		struct CFamilyHouse
		{
		};

		struct CGovernmentBuilding
		{
		};
	}

	struct CCityStatistics
	{
	};

	struct CTypeOfCommunication
	{
	};
}

Baltimore::CityStatistics;
Baltimore::Residences::FamilyHouse;

To use a nested namespace with the using keyword, use the same technique. Here is an example:

#using <mscorlib.dll>

using namespace System;

namespace Baltimore
{
	namespace Residences
	{
		struct CFamilyHouse
		{
		};

		struct GovernmentBuilding
		{
		};
	}

	struct CCityStatistics
	{

	};

	struct CTypeOfCommunication
	{
	};
}

int main()
{
         using namespace Baltimore;
	using namespace Baltimore::CResidences;

	CGovernmentBuilding;
	CCityStatistics;

         Console::WriteLine();
	return 0;
}
 

Accessories for Coding

 

Comments

A comment is a line or paragraph of text that the compiler would not consider when examining the code of a program. There are two types of comments recognized by C++.

To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:

// This line will be ignored. I can write in it anything I want

The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination would not be read by the compiler. Therefore, you can use this technique to span a comment on more than one line.

 

Escape Sequences

An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n.

An escape sequence can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n". Here are some of the supported escape sequences in C++:

Escape Sequence Name ASCII value Description
\a Bell (alert) 007 Makes a sound from the computer
\b Backspace 008 Takes the cursor back
\t Horizontal Tab 009 Takes the cursor to the next tab stop
\n New line 010 Takes the cursor to the beginning of the next line
\v Vertical Tab 011 Performs a vertical tab
\f Form feed 012 Form feed
\r Carriage return 013 Causes a carriage return
\" Double Quote 034 Displays a quotation mark (")
\' Apostrophe 039 Displays an apostrophe (')
\? Question mark 063 Displays a question mark
\\ Backslash 092 Displays a backslash (\)
\0 Null 000 Displays a null character

 

 

 

Home Copyright © 2004-2010 FunctionX, Inc. Next