Chapter 23. C Programming Basics

CONTENTS

Chapter 23. C++ Programming Basics

  •  Introduction
  •  C++ Basics
  •  Enhancements
  •  New Features of C++

Introduction

Programming languages have evolved in response to one primary issue: increasing complexity of programs. As a project increases in size, so does the ability to manage its complexity. At some point, the complexity exceeds the ability of a programmer to manage it. This situation has driven the need for better ways to manage complexity. Out of this need emerged object-oriented programming. C, already a popular language among programmers, did not support object- oriented programming. This prompted enhancements to C, and C++ was born.

C++ was built using C as a foundation, creating a smooth migration path to object-oriented programming for programmers already familiar with C. Because C++ is a superset of C, both C and C++ programs can be compiled with a C++ compiler. This capability implies that programmers need to make an effort to create object-oriented programs; the language does not force it.

The concepts and syntax already explored in the "C Language" section can be directly applied here. However, there are some differences where the C++ language has made syntax simplifications, enhancements, or introduced new concepts for object-oriented programming. These differences will be addressed in this section, first with enhancements to functionality already found in C, followed by new concepts and syntax added to the C++ standard.

For readers interested in programming with C++, this section should be supplemented with a book dedicated to C++ programming.

C++ Basics

A C++ program uses the same format as a C program. A C++ program may also have definitions of classes in header files or included in the source file. This will be addressed later in this section.

A C++ source file extension is .cpp.

Enhancements

As previously discussed, C++ has simplified some syntax and enhanced functionality already found in C. This section will discuss these differences.

Comments

C++ has simplified a single-line comment. A single-line comment is proceeded with a double forward slash (//):

// a single-line comment 

Comments can still start with /* and end with */, but these notations are typically reserved for multiple-line comments.

I/O System

I/O stands for input and output. I/O operations are how we get information read into or sent out of a program. In the "C Language" section, we used two of the C I/O functions, scanf() (input) and printf() (output).

C++ has defined its own I/O system, because it needs to handle more than just the base data types. C++ I/O is object-oriented and can be made aware of objects that a programmer creates. For more information on the C++ I/O system, refer to one of the recommended C++ books listed at the end of this chapter.

Output Statement

In C, the function printf() caused a message to be displayed on the screen. C++ allows us to use cout, which stands for console out:

cout << "Let's go to the beach\n"; 

The statement above outputs the string "Let's go to the beach" to the screen using the insertion operator (<<).

Variables can also be printed to the screen just as easily:

int num_rooms = 4;  cout << "My new house has " << num_rooms << " bedrooms."; 

When using count in a program, be sure to include the following processor directive:

#include <iostream>  using namespace std; 

For more information regarding the use of namespaces, refer to the "Namespace" section later in this chapter.

If your compiler is older, it may not support the new style headers. Both statements must be replaced with the following for an older compiler:

#include <iostream.h> 

Input Statement

In C, we used the scanf() function to read user-entered information from the keyboard. C++ provides cin, which stands for console in, although input is usually accepted from the keyboard:

int length;  cout << "Enter the length of the vehicle: ";  cin >> length; 

The code fragment above prompts the user for input, and then accepts input from the keyboard, using cin and the extraction operator (>>).

When using cin, be sure to include the following processor directive:

#include <iostream> using namespace std; 

For more information regarding the use of namespaces, refer to the "Namespace" section.

If your compiler is older, it may not support the new style headers. Both statements must be replaced with the following for an older compiler:

#include <iostream.h> 

Headers

Older versions of the C++ compiler force the use of the .h file extension for header files in #include statements. An example of an old style #include statement for the iostream header is as follows:

#include <iostream.h> 

This causes the preprocessor to include the iostream.h file in the program. The old style specification uses a file name. This is not the case for the newer C++ standard.

The newer C++ standard does not specify file names for header files; they specify standard identifiers. The headers are an abstraction that ensures that the appropriate information required by the program is included. The identifiers may or may not map to a file name. An example is as follows:

#include <iostream> 

When including the newer style C++ headers, the contents of the headers are contained in the std namespace. For more information regarding namespaces, see the "Namespace" section later in this chapter.

Enumerations

In C++, when declaring a variable of type enumeration Week, the following statement:

enum Week yesterday; 

can be written as:

Week yesterday; 

Precedence

The precedence of a few new operators needs to be included. Scope resolution (::) has the highest order of precedence; see the "Namespace" section later in this chapter for more information. C++ has included four new casting operators; see the "Casting Operators" section later in this chapter for more information.

Table 23-1 lists operators in their order of precedence, starting with the highest precedence.

Table 23-1. C++ Operators in Order of Precedence

Operator

Associativity

::

Left to right

( )

Left to right

unary +, unary -, sizeof(), ++, --, (type)

Right to left

static_cast, dynamic_cast, const_cast

 

reintrept_cast

 

*, /, %

Left to right

binary +, binary

Left to right

=, +=, -=, *=, /=, %=

Right to left

New Features of C++

The following features are part of the C++ standard and do not have their foundations in C. Many of these features provide enhanced capabilities and enable object-oriented programming.

Namespace

Namespaces are a recent addition to the C++ standard. For this reason, namespaces may not be supported in older C++ compilers.

Namespaces are designed to avoid name collisions. Prior to namespaces, all these names competed for slots in the global namespace. Global namespace or global scope can be thought of as an area outside all functions and classes. In both C and C++, any variable declared at the top of a source file, outside a function, will be global. This makes them accessible by all functions. Contention for names in the global namespace has become an issue, especially in the C++ programming environment, where there are a larger number of variable, function, and class names.

For example, the standard library contains a function called abs(), which returns the absolute value of an integer. If a program defined its own function called abs(), it would collide in the global namespace with the standard library function abs(). Even if the programmer was careful to use a function name not found in the standard library, there still could be a collision with third-party libraries. It becomes impossible to guarantee the uniqueness of a function, variable, or class name.

A namespace is a region within a program that is assigned its own name, and all names declared within that region are local to that namespace. Any names declared within a namespace will have the name of the namespace associated with them. Figure 23-1 illustrates two namespaces.

Figure 23-1. Two Namespaces

graphics/23fig01.gif

In each namespace there is a variable called area. Each variable is associated with separate namespaces. They may look the same, but the actual variable names are circle::area and square::area. The same holds true for the functions circle::find_area() and square::find_area(). This naming prevents any potential clashes between them.

The standard library namespace is std. Any names defined in the standard library have the std name associated with them. For example, the complete name of the console out statement, cout, is std::cout. A statement to display the contents of a variable can be written as:

std::cout << value1; 

The operator:: is the scope resolution operator. This operator tells the compiler where to look for the definition of a name. In the example above, the compiler will look for the definition of cout in the standard library.

The using directive allows all the names in the namespace to be used without qualification. The format of the using directive is:

using namespace namespace_name; 

The namespace can be declared at the top of a function. When the namespace is declared this way, it is no longer necessary to use the namespace, scope resolution operator, and the name. Just the name can be used. This fact is illustrated with a code fragment that has the same operation as the example above:

. . .  using namespace std;  . . .  cout << value1;  . . . 

This simplifies the code, but needs to be used with caution. Ambiguities can result.

For code simplification, a better solution would be using the using declaration instead of the using directive. The format of a using declaration is:

using namespace_name::identifier; 

If a program is using cout frequently, the using declaration can be used as follows:

using std::cout; 

More Data Types and Operators

C++ supports several other data types and operators. Also discussed will be dynamic memory allocation for C++.

Access Modifiers

There are two access modifiers that are used to control the way variables can be accessed and modified. The first, const, isalso part of C language. The second, volatile, is found only in C++.

When variables are declared with the const modifier, their values cannot be modified during the execution of the program. For example,

const int hours_in_day = 24; 

creates an integer variable called hours_in_day, which contains the value 24. This value cannot be modified during the execution of the program.

The volatile modifier tells the compiler that the variable's value may be modified asynchronously by an external process. The intent of this modifier is to prohibit the compiler from performing optimization on that variable. The compiler may optimize by referencing a previously loaded value for the variable to reduce overhead. The volatile modifier forces the value of the variable to be retrieved each time it is used.

For example, if a variable called time needs to be updated every second by the computer's clock mechanism, the compiler should not reuse the previously retrieved value. A new value must be obtained from the computer's clock mechanism. The variable time needs to be declared as:

volatile int time; 

This will ensure that the variable time will be populated with a new value each time it is referenced.

Dynamic Memory Allocation

C++ has two new operators for dynamic memory allocation: new and delete. New allocates memory, and delete de-allocates or frees memory allocated by new. The formats are as follows:

pointer_variable = new data_type;  delete pointer_variable; 

The pointer_variable is a pointer of type data_type. The new operator allocates sufficient memory to hold a value of type data_type and returns a pointer to it.

The delete operator frees the memory pointed to by pointer_variable.

Memory can be initialized when using the new operator by specifying a value inside the parentheses after the data_type. For example:

#include <iostream>  using namespace std;  int main()  {              int *num_ptr;               num_ptr = new int (346); // initialize with 346               if (!num_ptr)               {                   cout << "Memory allocation failure.\n");                    return 1;               }               cout << "Memory was successfully                      allocated for num_ptr contajning " << *p;               delete p;// clean up memory               return 0;  } 

Arrays can also be allocated using new. To allocate a single dimension array:

pointer_variable = new variable_type[size]; 

Size refers to the number of elements in the array.

To free a dynamically allocated array, use:

delete [ ] pointer_variable;

Function Overloading

Function overloading is a feature in C++ where two or more functions can share the same name, as long as their parameter declarations are different. When functions are sharing the same name, they are said to be overloaded. Function overloading is one way that C++ achieves polymorphism.

Consider the following program:

// overload the function three times  #include <iostream>  using namespace std;  void print_values( int x );// function prototypes - integer param  void print_values( int x, int y);// two integer parameters  void print_values(double z );// double parameter  int main()  {               print_values(346);                print_values(3, 346);                print_values(10.25);                return 0;  }  void print_values(int x )  {               cout << "The value is " << x;  }  void print_values(int x, int y)  {               cout << "The value is " << x << " and " << y;  }  void print_values(double z)  {               cout << "The value is " << z;  } 

The print_values() function is overloaded three times, allowing the function to accept three different parameter lists.

Overloading of a function is intended for closely related operations. For example, overloading a function called square(), once for the square of an integer and the other for the square root of a floating point number, would not be good programming practice. The variations of the overload function are not closely related. If the square() function accepted an integer and squared it, and overloaded the function to accept a floating-point number and squared it, this would be a case where operations were closely related and overloading makes sense.

Default Function Arguments

C++ allows a parameter to have a default value if the function is called with no corresponding value. For example, if a function is called with an integer and a character in the parameter list, each of these values can be given a default value:

void price_widgets(int num_widgets = 1, char widget_type = 'A')  {               // code for pricing widgets                . . .  } 

The function is then called in the following ways:

price_widgets( 3, 'D' ); // passes values to all parameters  price_widgets( 7);        // passes in the number of widgets,                           // but uses the default value                           // for the widget type  price_widgets();        // uses default values for both parameters 

The first function call passes values to all the parameters. Because the second function call does not have a value for widget_type, the default of 'A' is used. In the third function call, both parameters are not passed; the default values of 1 for the number of widgets and 'A' for the widget type are used.

Classes

The class is the foundation of C++'s support for object-oriented programming. It allows programs to be written in terms of objects.

The keyword class is used to define a new data type, a data type that can be used to create objects. A class defines and contains both the data and the code that operates upon the data. The packaging together of data members and functions that operate on the data within an object is referred to as encapsulation.

When a class is declared, an object is created. The object is the physical existence that occupies space in memory and is an instance of the class. Each object of a class has its own copy of the data defined within the class. The format of a class declaration is as follows:

class class_name {                   private data and functions   public:                    public data and functions  } object_list; 

Private data and functions are usable only by the functions within the class. Any private data and functions are inaccessible and are protected from outside interference. This protection is known as data hiding.

If a program managed bank accounts, the data within the accounts needs to be protected from other parts of the program that may attempt to directly access or change the account balance. A class would provide that protection by declaring account balances as private. An example of a class may be:

// This creates a class for a bank account  class bank_acct {                 double acct_balance;               public:                  void init();                  double retrieve_balance();                  void update_balance();                  . . .  }; 

By default, all items in a class are private. In this class, acct_balance is private and can only be accessed by other members of the bank_acct class. All items defined after the public specifier are accessible by all other functions in the program. Typically, the program will access the private items within a class through its public functions. The functions init(), retrieve_balance(), and update_balance() are called member functions and make up the public interface. Because the prototypes for the member functions are within the class definition, they do not need to be prototyped elsewhere.

After the class has been defined, an object can be created of that type by using the class name. The class name becomes a new data type specifier. To create two objects, checking and savings, the following statement is used:

bank_acct checking, savings; 

To implement a member function such as retrieve_balance(), the compiler must be told which class the function belongs to by qualifying the function name with the class name. The source code for retrieve_balance() function is:

double bank_acct::retrieve_balance()  {              return( acct_balance );  } 

The :: symbol is the scope resolution operator. This tells the compiler that this version of the function, retrieve_balance(), belongs to the class bank_acct.

To call a member function from part of the program that is not part of the class, the object's name and the dot operator must be used. The following is a call to the retrieve_balance() function for object checking:

bank_acct checking, savings;  double checking_balance;  checking_balance = checking.retrieve_balance(); 

This will retrieve the account balance for the checking object only.

Constructor

It is common for some part of an object to require initialization at the time it is created. In the bank_acct class, the acct_balance should be set to 0.0. This is done with a constructor function. If a constructor function is not provided, the compiler will supply a default constructor. The object for the class is created in a constructor, which is all the default constructor will do.

A constructor function is a special function that is a member of a class and has the same name as a class. When the object is created, the object's constructor is called. An example of a constructor function for the class bank_acct is:

// Constructor function  bank_acct::bank_acct()  {              acct_balance = 0.0;  } 

For global objects, the constructor is called before the main() function. For local objects, the constructor is called each time an object declaration is encountered.

A constructor can also accept parameters. It would look as follows:

// This creates a class for a bank account  class bank_acct {              double acct_balance;  public:               bank_acct(double starting_balance);                         // constructor accepting a parameter               ~bank_acct();           // destructor               void init();               double retrieve_balance();               void update_balance();               . . .  };  // constructor function  bank_acct::bank_acct( double balance )  {              acct_balance = balance;  } 

The argument to the constructor function is passed in when the object is declared using either method below:

bank_acct checking = bank_acct( 120.05 ); 

or

bank_acct checking( 120.05 ); 
Destructor

When objects are destroyed, the destructor function is called. This function is called when the object is destroyed.

A destructor function is a member of a class and has the same name of the class, but the destructor's name is preceded with ~. An example of a destructor function for the class bank_acct is:

// Destructor Function  bank_acct::~bank_acct()  {              // write account information to a log file               . . .  } 

If the source code for a function, constructor, or destructor resides within the class, the class name and scope resolution operator are not needed.

Friend Functions

Members of a class can be private or public. Private ensures that only other members of the class can use anything private. Public members are accessible by other classes and functions outside the scope of the class in which they are declared.

A function that is not a member of a class but can access all its members is called a friend function. This allows non-member functions to access the private members of a class. To make a function a friend of a class, use the friend keyword in the public section of the class, and include the function's prototype. For example:

// This creates a class for a bank account  class bank_acct {                double acct_balance;  public:                 bank_acct(double starting_balance);                                  // constructor accepting a parameter                 ~bank_acct();    // destructor                 void init();                 double retrieve_balance();                 void update_balance();                 friend void irs_audit(bank_acct x);                         // irs_audit function is not part of the class                 . . .    // but can access private members  };  // irs_audit function - NOTE it is not a member function of any class  void irs_audit( bank_acct x )  {               // code for audit                . . .  } 

The irs_audit() function can access all members of the class bank_acct directly. For example, the irs_audit() function can access the account balance in the bank_acct class using:

x.acct_balance; 

String Objects

C++ provides a string type, which is defined by a class. Essentially, a class simply introduces a new type in the language. In practice, using a class-defined type is no different from using one of the basic data types.

Null-terminating strings, like those used in C, cannot be manipulated by any of the standard C++ operators. The standard string class was introduced to solve this issue as well as for convenience and to prevent the overrun of array boundaries.

Declaring a String Object

An object of type string contains a string of characters of type char. To declare an object of type string as an empty string, use the following statement:

string student_name; 

To declare and initialize a string, use:

string student_name = "Glenn"; 

or, by using a function notation, as in:

string student_name ( "Glenn" ); 

The stored string does not need a null-terminating character. The string object keeps track of the length of the string.

String Assignment

A string can be assigned a value of a string literal or another string, simply by using the assignment operator.

string valedictorian = "Carly";// declares and initializes a string  string student_1 = "Liz";      // declares and initializes a string  valedictorian = student_1;     // modifies contents of valedictorian 
Concatenation

Strings can be joined together using the addition operator; this is known as concatenation. The following example demonstrates concatenation:

string valedictorian = "Carly";// declares and initializes a string  string student_1 = "Liz";// declares and initializes a string  string announcement = valedictorian + " and " + student_1 + " have  won awards." 
Comparison

When entire strings need to be compared, string objects can be used with any of the comparison operators. The comparison operators are:

>      >=      <      <=      ==      != 

An example of string comparisons is:

string animal_1 = "dog";  string animal_2 = "cat";  if (animal_1 == animal_2 )               cout << "Both animals are the same.\n");  else               cout << "These animals are different.\n"); 

Inheritance

Inheritance allows new classes to be created by reusing and expanding existing classes. C++ supports inheritance by allowing one class to incorporate another class into its declaration.

A base class is used to create a new, specialized class or derived class, as shown in Figure 23-2.

Figure 23-2. Base Class Creates a New Derived Class

graphics/23fig02.gif

The format for inheritance is as follows:

Class derived_class : access base_class  {              body of new class  } 

Access is optional, but if it is present, it must be public, private, or protected.

The following class, automobile, is a generic and broad description of a car. It gives the number of doors, number of wheels, and number of cylinders in the engine:

class automobile  {                int doors;                 int wheels;                 int cylinders;  public:                 void set_doors(int num_d) {door = num_d; }                 int get_doors() { return doors; }                 void set_wheels(int num_w) {wheels = num_w; }                 int get_wheels() { return wheels; }                 void set_cylinders(int num_c) {cylinders = num_c; }                 int get_cylinders() { return cylinders; }  }; 

This base definition of an automobile can beused tohelp define a specific object. For example, this base class, automobile, can be used to define a class called station_wagon:

class station_wagon : public automobile  {              int hatch_space;  public:               void set_hatch(int size)  {hatch_space = size; }               int get_hatch() { return hatch_space; }               void display_features();  }; 

Because station_wagon inherits automobile, the class station_wagon includes all members of the class automobile and adds information and member functions about the hatch space in the back of the vehicle for cargo.

Access Control

When one class inherits from another, the members of the base class become members of the derived class. The ability to access the base class members inside the derived class is determined by the access specifier used in the inheritance declaration.

The base class can have access specifiers of public, private, or protected. If the access specifier is not included in the inheritance declaration, the default of private is used. But this is only true if the derived class is a class. A derived class may also be a structure, and in that case, the default access is public.

What are the implications of all this specification? The access specifier affects the ability of the derived class to access members of the base class.

First of all, individual members of a class can be declared as public, private, or protected. A public member of a class is accessible by the class and anything external to the class. A private member of the class is only accessible by member functions of the class. A protected class member allows access to a derived class when inherited; otherwise, it behaves like a private member of the class.

Inheritance affects the access of base class member functions, and the base class also has an access specifier associated with it. When a class is derived or inherits from a base class, a base class access specifier of public, private, or protected is chosen. The impact to the base class members can be described in a total of nine combinations of base class access and member function access.

When the inheritance of the base class is public, the access status of the inherited members is unchanged. (1.) Inherited public members are public, (2.) inherited protected members are protected, and (3.) inherited private members are private.

When the inheritance of the base class is protected, (4.) inherited public members of the base class become protected members in the derived class. (5.) The inherited protected members of the base class remain protected. (6.) The inherited private members of the base class remain private.

When the inheritance of the base class is private, (7.) inherited public and (8.) protected members of the base class become private to the derived class. They are accessible by member functions of the derived class but not accessible outside the derived class, even when the derived class is inherited by another derived class. (9.) Private members of the base class remain private in the derived class.

Polymorphism

Polymorphism is an advanced topic in C++. An overview will be addressed here. C++ polymorphism is the process by which different implementations of a function can be accessed via the same name and is sometimes referred to as "one interface, multiple methods." Polymorphism only operates within a class hierarchy, making the ability to derive one class from another a fundamental capability.

C++ polymorphism is supported at both compile time and runtime. Function overloading is an example of compile-time polymorphism. C++ also allows runtime polymorphism via derived classes and virtual functions.

Base Class Pointers

The foundation of runtime polymorphism is the base class pointer. Pointers to base classes and derived classes have a special relationship that differs from other pointers. We've previously seen that a pointer of one type cannot point to an object of another type. Base class pointers and derived objects are the exception to the rule. A base class pointer can be used to point to an object of any class derived from that base. For example, given the base class of automobile and the derived class of station_wagon, any pointer declared as a pointer to automobile can also be a pointer to station_wagon:

class automobile  {                int doors;                 int wheels;                 int cylinders;  public:                 void set_doors(int num_d) {door = num_d; }                 int get_doors() { return doors; }                 void set_wheels(int num_w) {wheels = num_w; }                 int get_wheels() { return wheels; }                 void set_cylinders(int num_c) {cylinders = num_c; }                 int get_cylinders() { return cylinders; }  };  class station_wagon : public automobile  {                int hatch_space;  public:                 void set_hatch(int size)  {hatch_space = size; } int  get_hatch() { return hatch_space; }                 void display_features();  }; 

Given the following:

automobile p*;           // pointer to object of type automobile  automobile auto_object; // object of type automobile station_wagon  stwgn_object;           // object of type station_wagon 

both statements below are valid:

p = &auto_object;  // pointer points to object of type automobile  p = &station_wagon;// pointer points to object of type station_wagon 

The pointer p can access all elements of station_wagon inherited from automobile. However, elements specific to type station_wagon cannot be referenced with p unless a type cast is used.

Virtual Functions

Polymorphism is accomplished through a combination of inheritance and virtual functions.

A virtual function is declared as virtual in the base class and is redefined in one or more derived classes. This definition allows each derived class to have its own version of the virtual function. A virtual function is called through a base class pointer. C++ determines which version of the virtual function to call based upon the type of the object pointed to by the pointer at runtime. The compiler dynamically binds the function in any class that is derived from the base class. The type of object pointed to determines the version of the virtual function to execute.

The following program demonstrates the use of virtual functions:

#include <iostreadm>  using namespace std;  class base_print  { public:                 virtual void print_me()                 {                cout << "Print statement from the base class.\n";                 }  };  class first_print : public base_print  { public:                 void print_me() { cout << "Print statement from                                            first_print class.\n"; }  };  class second_print : public base_print  { public:                 void print_me() { cout << "Print statement from                                            second_print class.\n" }  };  int main()  {                base_print base_object;                 base_print ptr;                 first_print first_object;                 second_print second_object;                 p = & base_object;                 p->print_me();// prints from base_print class                 p = &first_object;                 p->print_me();// prints from first_object class                 p = &second_object;                 p->print_me();// prints from second_object class                 return 0;  } 

The program prints:

Print statement from the base class.  Print statement from the first_print class.  Print statement from the second_print class. 

Casting Operators

In addition to the traditional method of casting seen in the "C Language" section, C++ has defined four casting operators: dynamic_cast, const_cast, reinterpret_cast, andstatic_ cast. These operators were added to enable additional control over how casting is performed.

dynamic_cast

The dynamic_cast verifies the validity of a cast at runtime. The purpose of a dynamic_cast is to perform casts on polymorphic types. Basically, a dynamic_cast will succeed if the pointer or reference being cast is a pointer or reference to either an object of the target type or an object derived from the target type.

The format of a dynamic_cast is:

dynamic_cast<target_type> (expression) 
const_cast

The const_cast is used to override a const or volatile in a cast. The format of a const_cast is:

const_cast<target_type> (expression) 
static_cast

A static_cast performs a non-polymorphic cast. This is a substitute for the original cast operator, discussed in the "C Language" section. The format of a static_cast is:

static_cast<data type>(expression) 
reinterpret_cast

A reinterpret_cast operator converts a type into a fundamentally different type. For example, it can change a pointer into an integer and vice versa. It can also be used to cast incompatible pointer types. The format of a reinterpret_cast is:

reinterpret_cast<data_type>(expression) 

Exception Handling

An exception is an error that occurs at runtime. C++ allows programmers to handle runtime exceptions in a controlled manner. Errors or exceptions can be caught and handled easily with an error handling routine.

There are three keywords for exception handling: try, catch, and throw. Programming statements to be monitored are contained in a try block. If an exception occurs within the try block, it is thrown using throw. The exception is caught using catch and is processed by an error-handling routine.

The throw generates an exception based upon the error encountered. The throw is executed from within a try block or from a function within the try block. The format for a throw statement is:

throw exception; 

The general form of a try and catch is:

try  {              // statements to check for errors - try block               // contains a throw statement or a function               // that contains a throw statement  }  catch (type1 arg)  {              // catch block  }  catch (type2 arg)  {              //catch block  }               . . .  catch (typeN arg)  {              // catch block  } 

The C++ programming section was intended to give you a quick overview and should be supplemented with a C++ programming book to provide more detail and comprehensive coverage of the topics we've just touched upon.

CONTENTS


UNIX User's Handbook
UNIX Users Handbook (2nd Edition)
ISBN: 0130654191
EAN: 2147483647
Year: 2001
Pages: 34

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net