Sie sind auf Seite 1von 10

The Object-Oriented Approach OOP is a way of organizing programs.

The emphasis is on the way programs are designed, not on coding details. The fundamental idea behind object-oriented languages is to combine into a single unit both data and the functions that operate on that data. Such a unit is called an object. An objects functions, called member functions in C++, typically provide the only way to access its data. If you want to read a data item in an object, you call a member function in the object. It will access the data and return the value to you. You cant access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are said to be encapsulated into a single entity. If you want to modify the data in an object, you know exactly what functions interact with it: the member functions in the object. No other functions can access the data. This simplifies writing, debugging, and maintaining the program. A C++ program typically consists of a number of objects, which communicate with each other by calling one anothers member functions. The organization of a C++ program is shown in Figure 1.3.

Characteristics of Object-Oriented Languages

Lets briefly examine a few of the major elements of object-oriented languages in general, and C++ in particular. Objects When you approach a programming problem in an object-oriented language, you no longer ask how the problem will be divided into functions, but how it will be divided into objects. Thinking in terms of objects, rather than functions, has a surprisingly helpful effect on how easily

programs can be designed. This results from the close match between objects in the programming sense and objects in the real world. Classes In OOP we say that objects are members of classes. A class serves as a plan, or template. It specifies what data and what functions will be included in objects of that class. A class is thus a description of a number of similar objects. Prince, Sting, and Madonna are members of the class of rock musicians. There is no one person called rock musician, but specific people with specific names are members of this class if they possess certain characteristics. Inheritance an OOP class can be divided into subclasses. In C++ the original class is called the base class; other classes can be defined that share its characteristics, but add their own as well. These are called derived classes. Reusability Once a class has been written, created, and debugged, it can be distributed to other programmers for use in their own programs. This is called reusability. However, in OOP, the concept of inheritance provides an important extension to the idea of reusability. A programmer can take an existing class and, without modifying it, add additional features and capabilities to it. This is done by deriving a new class from the existing one. The new class will inherit the capabilities of the old one, but is free to add new features of its own. Creating New Data Types One of the benefits of objects is that they give the programmer a convenient way to construct new data types. Many features of C++ are intended to facilitate the creation of new data types in this manner. Polymorphism and Overloading Using operators or functions in different ways, depending on what they are operating on, is called polymorphism (one thing with several distinct forms). When an existing operator, such as + or =, is given the capability to operate on a new data type, it is said to be overloaded. Overloading is a kind of polymorphism; it is also an important feature of OOP.

#include <iostream> using namespace std; int main() { cout << Every age has a language of its own\n; return 0; }

The two lines that begin the program are directives. The first is a preprocessor directive, and the second is a using directive. Preprocessor Directives The first line of the program is called a preprocessor directive. A preprocessor directive, on the is an instruction to the compiler. A part of the compiler called the preprocessor deals with these directives before it begins the real compilation process.

The preprocessor directive #include tells the compiler to insert another file into your source file. In effect, the #include directive is replaced by the contents of the file indicated. The type file usually included by #include is called a header file. The using Directive A C++ program can be divided into different namespaces. A namespace is a part of the program in which certain names are recognized; outside of the namespace theyre unknown. The directive using namespace std; says that all the program statements that follow are within the std namespace. Various program components such as cout are declared within this namespace. The #define Directive constants can be specified using the preprocessor directive #define. This directive sets up an equivalence between an identifier and a text phrase. For example, the line
#define PI 3.14159

appearing at the beginning of your program specifies that the identifier PI will be replaced by the text 3.14159 throughout the program. Conditional directives guard against the multiple processing of a header file. For example:
#ifndef BOOKSTORE_H #define BOOKSTORE_H /* Bookstore.h contents go here */ #endif

The conditional directive


tests whether BOOKSTORE_H has not been defined previously. BOOKSTORE_H is a preprocessor constant. If BOOKSTORE_H has not been previously defined, the conditional directive evaluates as true and all the lines following #ifndef until the #endif is found are included and processed. Conversely, if the #ifndef directive evaluates as false, the lines between it and the #endif directive are ignored. To guarantee that the header file is processed only once, we put the #define directive #define BOOKSTORE_H following the #ifndef. In this way, BOOKSTORE_H is defined the first time that the content of the header file is processed, preventing the #ifndef directive from evaluating as true in further evaluations in the program text file. The #ifdef directive is most frequently used to conditionally include program code depending on whether a preprocessor constant is defined. For example: int main() { #ifdef DEBUG cout << "Beginning execution of main()\n"; #endif string word; vector< string > text; while ( cin >> word ) {

#ifdef DEBUG cout << "word read: " <<word << "\n"; #endif text.push_back( word ); } // ... } In this example, if DEBUG is not defined, the program code actually compiled is int main() { string word; vector< string > text; while ( cin >> word ) { text.push_back( word ); } } Otherwise, if DEBUG is defined, the program code passed to the compiler is as follows: int main() { cout <<"Beginning execution of main()\n"; string word; vector< string > text; while ( cin >> word ) { cout << "word read: " <<word << "\n"; text.push_back( word ); } }

Exceptions provide a systematic, object-oriented approach to handling run-time errors generated by C++ classes. Exceptions are errors that occur at run time. They are caused by a wide variety exceptional circumstance, such as running out of memory, not being able to open a file, trying to initialize an object to an impossible value, or using an out-of-bounds index to a vector. Sometimes, an application makes a mistake, causing an error to be detected in a member function. This member function then informs the application that an error has occurred. When exceptions are used, this is called throwing an exception. In the application we install a separate section of code to handle the error. This code is called an exception handler or catch block; it catches the exceptions thrown by the member function. Any code in the application that uses objects of the class is enclosed in a try block. Errors generated in the try block will be caught in the catch block. Code that doesnt interact with the class need not be in a try block.

The exception mechanism uses three new C++ keywords: throw, catch, and try. Also, we need to create a new kind of entity called an exception class. XSYNTAX is not a working program, but a skeleton program to show the syntax.
// xsyntax.cpp // not a working program class AClass //a class { public: class AnError //exception class { }; void Func() //a member function { if( /* error condition */ ) throw AnError(); //throw exception } }; int main() //application { try //try block { AClass obj1; //interact with AClass objects obj1.Func(); //may cause error } catch(AClass::AnError) //exception handler { //(catch block) //tell user about error, etc. } return 0; }

We start with a class called AClass, which represents any class in which errors might occur. An exception class, AnError, is specified in the public part of AClass. In AClasss member functions we check for errors. If we find one, we throw an exception, using the keyword throw followed by the constructor for the error class:
throw AnError(); //throw followed by constructor for AnError class In the main() part of the program we enclose any statements that interact with AClass in a try block. If any of these statements causes an error to be detected in an AClass member function,

an exception will be thrown and control will go to the catch block that immediately follows the try block.

4 Variable Type Summary

Table 2.2 Basic C++ Variable Types Numerical Range Keyword Low High Char 128 127 short 32,768 32,767 int 2,147,483,648 2,147,483,647 long 2,147,483,648 2,147,483,647 float 3.4 x 1038 3.4 x 1038 Digits of Precision n/a n/a n/a n/a 7 Bytes of Memory 1 2 4 4 4

double long double

1.7 x 10308 3.4 x 104932

1.7 x 10308 1.1 x 104932

15 19

8 10

int main() { int var1; //define var1 int var2; //define var2 var1 = 20; //assign value to var1 var2 = var1 + 10; //assign value to var2 cout << var1+10 is ; //output text cout << var2 << endl; //output value of var2 return 0; } int main() { char charvar1 = A; //define char variable as character char charvar2 = \t; //define char variable as tab cout << charvar1; //display character cout << charvar2; //display character charvar1 = B; //set char variable to char constant cout << charvar1; //display character cout << \n; //display newline character return 0; } int main() { float rad; //variable of type float const float PI = 3.14159F; //type const float cout << Enter radius of circle: ; //prompt cin >> rad; //get radius float area = PI * rad * rad; //find area cout << Area is << area << endl; //display answer return 0; }

Type bool
Variables of type bool can have only two possible values: true and false. In theory a bool type requires only one bit (not byte) of storage, but in practice compilers often store them as integers because an integer can be quickly accessed, while an individual bit must be extracted from an integer, which requires additional time. unsigned Data Types By eliminating the sign of the character and integer types, you can change their range to start at 0 and include only positive numbers. This allows them to represent numbers twice as big as the signed type. Table 2.3 shows the unsigned versions. Table 2.3 Unsigned Integer Types Numerical Range Bytes of Keyword Low High Memory unsigned char 0 255 1 unsigned short 0 65,535 2

unsigned int unsigned long

0 0

4,294,967,295 4,294,967,295

4 4

5. Reference Arguments
A reference provides an aliasa different namefor a variable.A reference allows for the indirect manipulation of an object in a manner similar to the use of a pointer but without requiring use of pointer syntax. In real-world programs, references are primarily used as formal parameters to a functionusually to pass class objects into a function A reference type is defined by following the type specifier with the address-of operator. A reference must be initialized. For example: int ival = 1024; // ok: refVal is a reference to ival int &refVal = ival; Once defined, a reference cannot be made to refer to another object .

The const type qualifier transforms an object into a constant. For example, const int bufSize = 512; // input buffer size defines bufSize to be a constant initialized with the value 512. Any attempt to change that value from within the program results in a compile-time error. For this reason, it is referred to as readonly. An object is declared volatile when its value can possibly be changed in ways outside either the control or detection of the compiler for example, a variable updated by the system clock. For example: volatile int display_register; display_register is a volatile object of type int. The essential purpose of the volatile qualifier is to notify the compiler that the object can change in ways undetectable by the compiler. The compiler, therefore, should not aggressively optimize code referring to the object.

An extended set of basic data types is provided within the C++ standard library, including vector. The vector, is a class template. #include <vector> vector<string> chapter_titles( 20 ); chapter_titles is a vector of 20 elements of the string type. The peculiar syntax of vector<string> directs the compiler to create a vector type capable of holding string elements.

A variable that holds an address value is called a pointer variable, or simply a pointer. For eg int *ptr; The asterisk means pointer to. Thus the statement defines the variable ptr as a pointer to int. This is another way of saying that this variable can hold the addresses of integer variables.

C++ predefines a special address-of operator (&) that, when applied to an object, returns that object's address value. Thus, to assign pint to ival's memory address, we write int *pint; pint = &ival; // assign pint address of ival

Enumeration is a way of defining user data types. An enum declaration defines the set of all names that will be permissible values of the type. These permissible values are called enumerator. For eg
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

The enum type days_of_week has seven enumerators: Sun, Mon, Tue, and so on, up to Sat. An enumeration is a list of all possible values. Enumerated types work when you know in advance a finite (usually short) list of values that a data type can take on. Once youve declared the enum type days_of_week you can define variables of this type such as day1 and day2, defined in the statement
days_of_week day1, day2;

Variables of an enumerated type, like day1 and day2, can be given any of the values listed in the enum declaration. The typedef mechanism provides a general facility for introducing a mnemonic synonym for a built-in or user-defined data type. For example: typedef double wages; These typedef names can serve as type specifiers within the program: // double hourly, weekly; wages hourly, weekly; A typedef definition begins with the keyword typedef, followed by the data type and identifier. The identifier, or typedef name, does not introduce a new type but rather a synonym for the existing data type. A typedef name can appear anywhere in a program that a type name can appear.

compile errors. These are given by your compiler and prevent your program from running. Egs are syntax errors, undefined variables, functions etc
//Error program const double x = (1.0/(2.0/(3.0/(4.0/5.0))); //Forgot a bracket const double y = 5.0 + ; //Forgot to write somehing after the plus for (unsigned int i=0; i<10; ++i) { cout << "Hello world" << endl; const double z = 8.0 //Forgot semicolon return 0; }

Runtime errors occur when a program with no syntax errors asks the computer to do something that the computer is unable to reliably do. Common examples are:

Trying to divide by a variable that contains a value of zero Trying to open a file that doesn't exist

There is no way for the compiler to know about these kinds of errors when the program is compiled. For example, if you run the following program:
#include <iostream> int main() { int x; cout << "enter a number: "; cin >> x; return(0); }

and you type a letter instead of a number, you will either get a runtime error

8 The Bitwise Operators

Table Bitwise Operators. Operator Function Use ~ bitwise NOT ~expr << left shift expr1 <<expr2 >> right shift expr1 >> expr2 & bitwise AND expr1 & expr2 ^ bitwise XOR expr1 ^ expr2 | bitwise OR expr1 | expr2 &= bitwise AND assign expr1 &= expr2 ^= bitwise XOR assign expr1 ^= expr2 |= bitwise OR assign expr1 |= expr2 A bitwise operator interprets its operand(s) as an ordered collection of bits, either individually or grouped as fields. Each bit can contain either a 0 (off) or a 1 (on) value. A bitwise operator allows the programmer to test and set individual bits or bit-fields

Arithmetic Operators
Table Operator Arithmetic Operators. Function Use

* multiplication expr * expr / division expr / expr % remainder expr % expr + addition expr + expr subtraction expr - expr Division between integers results in an integer. If the quotient contains a fractional part, it is truncated. For example: int ival1 = 21 / 6; int ival2 = 21 / 7; result in both ival1 and ival2 being initialized with a value of 3. The % operator computes the remainder of division between two values; the first value is divided by the second. This operator can be applied only to operands of the integral types (char, short, int, and long). The % operator is alternatively spoken of as the modulus, or the remainder, operator.

The new and delete Expressions

Every program is provided with a pool of available memory it can use during program execution. This pool of available memory is referred to as the program's free store or heap. The allocation of memory at run-time is referred to as dynamic memory allocation. this is accomplished by applying the new expression to a type specifier, either that of a built-in type or a userdefined class type. The new expression returns a pointer to the newly allocated object. For example: int *pi = new int; allocates one object of type int from the free store, initializing pi with its address. The object actually allocated on the free store is uninitialized. We can specify an initial value as follows: int *pi = new int( 1024 ); This not only allocates the object but also initializes it with a value of 1,024. To dynamically allocate an array of objects, we write int *pia = new int[ 10 ]; This allocates an array of ten objects of type int from the free store, initializing pia with its address. The elements of the array, however, are uninitialized. All manipulation of the object is done indirectly through that address. When our use of the object is complete, we must explicitly return the object's memory to the free store. We do this by applying the delete expression to the pointer that addresses the object originally allocated through the new expression. For example: delete pi; deallocates the int object addressed by pi, returning it to the free store. delete [] pia; deallocates the array of ten int objects addressed by pia, returning the associated memory to the free store. The empty bracket pair between the delete keyword and the pointer to the array represents the special delete expression syntax for deallocating an array allocated through the new expression.