C++ course / PDF

C++ course / PDF


C++ course / PDF








Part 1: Mechanics
Part 2: Basics
Part 3: References
Part 4: Const
Part 5: Inheritance
Part 6: Libraries
Part 7: Conclusion



*********




Part 1: Mechanics

C++ is a superset of C

•New Features include
–Classes (Object Oriented)
–Templates (Standard Template Library)
–Operator Overloading

–Slightly cleaner memory operations

Header Guards
#ifndef __SEGMENT_HEADER__
#define __SEGMENT_HEADER__
// contents of Segment.h
//...
#endif

•To ensure it is safe to include a file more than once.

Part 2: Basics

Allocating memory using new
Point *p = new Point(5, 5);
•new can be thought of a function with slightly strange syntax
•new allocates space to hold the object.
•new calls the object’s constructor.

•new returns a pointer to that object

Deallocating memory using delete

// allocate memory
Point *p = new Point(5, 5);
...
// free the memory
delete p;
For every call to new, there must be
exactly one call to delete.

Using new with arrays
int x = 10;
int* nums1 = new int[10]; // ok
int* nums2 = new int[x]; // ok
•Initializes an array of 10 integers on the heap.
•C++ equivalent of the following C code
int* nums = (int*)malloc(x * sizeof(int));

Using new with multidimensional arrays
int x = 3, y = 4;
int** nums3 = new int[x][4];// ok
int** nums4 = new int[x][y];// BAD!
•Initializes a multidimensional array
•Only the first dimension can be a variable. The rest must be constants.
•Use single dimension arrays to fake multidimensional ones

Using delete on arrays
// allocate memory
int* nums1 = new int[10];
int* nums3 = new int[x][4][5];
...
// free the memory
delete[] nums1;
delete[] nums3;
•Have to use delete[].

Destructors
•delete calls the object’s destructor.
•delete frees space occupied by the object.
•A destructor cleans up after the object.
•Releases resources such as memory.
















C++ course / PDF
2

Object Lessons From Lippman, C++ Object Model / PDF

Object Lessons From Lippman, C++ Object Model / PDF






Object Lessons From Lippman, C++ Object Model / PDF




















Introduction

In C, a data abstraction and the operations that perform on it are declared separately—that is, there is no language-supported relationship between data and functions. We speak of this method of programming as procedural, driven by a set of algorithms divided into task-oriented functions operating on shared, external data. For example, if we declare a struct Point3d, such as the following:

typedef struct point3d 
{ 
   float x; 
   float y; 
   float z; 
} Point3d; 
the operation to print a particular Point3d might be defined either as a function
void 
Point3d_print( const Point3d *pd ) 
{ 
   printf(”( %g, %g, %g )”, pd->x, pd->y, pd->z ); 
} 
or, for efficiency, as a preprocessor macro:
#define Point3d_print( pd )  \ 
   printf(”( %g, %g, %g )”, pd->x, pd->y, pd->z ); 
Or it may be directly implemented within individual code segments:
void 
my_foo() 
{ 
   Point3d *pd = get_a_point(); 
   ... 
   /* print the point directly ... */ 
   printf(”( %g, %g, %g )”, pd->x, pd->y, pd->z ); 
} 
Similarly, a particular coordinate member of a point is accessed either directly:
Point3d pt; 
pt.x = 0.0; 
or through a preprocessor macro:
#define X( p, xval ) (p.x) = (xval); 
... 
X( pt, 0.0 ); 
In C++, Point3d is likely to be implemented either as an independent abstract data type (ADT):
class Point3d 
{ 
public: 
   Point3d( float x = 0.0, 
            float y = 0.0, float z = 0.0 ) 
      : _x( x ), _y( y ), _z( z ) {} 
 
   float x() { return _x; } 
   float y() { return _y; } 
   float z() { return _z; } 
 
   void x( float xval ) { _x = xval; } 
 
   // ... etc ... 
private: 
   float _x; 
   float _y; 
   float _z; 
}; 
inline ostream& 
operator<<( ostream &os, const Point3d &pt ) 
{ 
   os << ”( ” << pt.x() << ”, ” 
      << pt.y() << ”, ” << pt.z() << ” )”; 
}; 
or as a two- or three-level class hierarchy:
class Point { 
public: 
   Point( float x = 0.0 ) : _x( x ) {} 
 
   float x() { return _x; } 
   void x( float xval ) { _x = xval; } 
   // ... 
protected: 
   float _x; 
}; 
 
class Point2d : public Point { 
public: 
   Point2d( float x = 0.0, float y = 0.0 ) 
      : Point( x ), _y( y ) {} 
 
   float y() { return _y; } 
   void y( float yval ) { _y = yval; } 
 
   // ... 
protected: 
   float _y; 
}; 
 
class Point3d : public Point2d { 
public: 
   Point3d( float x = 0.0, float y = 0.0, float z = 0.0 ) 
      : Point2d( x, y ), _z( z ) {} 
 
   float z() { return _z; } 
   void z( float zval ) { _z = zval; } 
 
   // ... 
protected: 
   float _z; 
}; 
Moreover, either of these implementations may be parameterized, either by the type of the coordinate:
template < class type > 
class Point3d 
{ 
public: 
   Point3d( type x = 0.0, 
            type y = 0.0, type z = 0.0 ) 
      : _x( x ), _y( y ), _z( z ) {} 
 
   type x() { return _x; } 
   void x( type xval ) { _x = xval; } 
 
   // ... etc ... 
private: 
   type _x; 
   type _y; 
   type _z; 
}; 
or by both the type and number of coordinates:
template < class type, int dim > 
class Point 
{ 
public: 
   Point(); 
   Point( type coords[ dim ] ) { 
      for ( int index = 0; index < dim; index++ ) 
         _coords[ index ] = coords[ index ]; 
   } 
 
   type& operator[]( int index ) { 
      assert( index < dim && index >= 0 ); 
      return _coords[ index ]; } 
 
   type  operator[]( int index ) const 
      { /* same as non-const instance */ } 
 
   // ... etc ... 
private: 
   type _coords[ dim ]; 
}; 
inline 
template < class type, int dim > 
ostream& 
operator<<( ostream &os, const Point< type, dim > &pt ) 
{ 
   os << ”( ”; 
   for ( int ix = 0; ix < dim-1; ix++ ) 
      os << pt[ ix ] << ”, ” 
   os << pt[ dim–1]; 
   os << ” )”; 
} 

These are obviously not only very different styles of programming, but also very different ways of thinking about our programs. There are many more or less convincing arguments for why the data encapsulation of an ADT or class hierarchy is better (in the software engineering sense) than the procedural use of global data such as that in C programs. Those arguments, however, are often lost on programmers who are charged with getting an application up and running quickly and efficiently. The appeal of C is both its leanness and its relative simplicity.

The C++ implementations of a 3D point are more complicated than their C counterpart, particularly the template instances. This doesn’t mean they are not also considerably more powerful or, again in a software engineering sense, better. But being more powerful or better is not necessarily a convincing argument for their use.

Section : Layout Costs for Adding Encapsulation

An obvious first question a programmer might ask while looking at the transformed Point3d implementations under C++ concerns the layout costs for adding encapsulation. The answer is that there are no additional layout costs for supporting the class Point3d. The three coordinate data members are directly contained within each class object, as they are in the C struct. The member functions, although included in the class declaration, are not reflected in the object layout; one copy only of each non-inline member function is generated. Each inline function has either zero or one definition of itself generated within each module in which it is used. The Point3d class has no space or runtime penalty in supporting encapsulation. As you will see, the primary layout and access-time overheads within C++ are associated with the virtuals, that is,
  • the virtual function mechanism in its support of an efficient run-time binding, and
  • a virtual base class in its support of a single, shared instance of a base class occurring multiple times within an inheritance hierarchy.
There is also additional overhead under multiple inheritance in the conversion between a derived class and its second or subsequent base class. In general, however, there is no inherent reason a program in C++ need be any larger or slower than its equivalent C program.

Section 1.1: The C++ Object Model

In C++, there are two flavors of class data members—static and nonstatic—and three flavors of class member functions—static, nonstatic, and virtual. Given the following declaration of a class Point:
class Point 
{ 
public: 
   Point( float xval ); 
   virtual ~Point(); 
 
   float x() const; 
   static int PointCount(); 
 
protected: 
   virtual ostream& 
      print( ostream &os ) const; 
 
   float _x; 
   static int _point_count; 
}; 
how is the class Point to be represented within the machine? That is, how do we model the various flavors of data and function members?

Section : A Simple Object Model

Our first object model is admittedly very simple. It might be used for a C++ implementation designed to minimize the complexity of the compiler at the expense of space and runtime efficiency. In this simple model, an object is a sequence of slots, where each slot points to a member. The members are assigned a slot in the order of their declarations. There is a slot for each data or function member........ 



















Object Lessons From Lippman, C++ Object Model / PDF

2

Free tutorial : Basic Elements of C++


Free tutorial : Basic Elements of C++


Free tutorial : Basic Elements of C++








Overview

    
·         Chapter 2 teaches your students the basics of C++. Learning a programming language is similar to learning to be a chef or learning to play a musical instrument. All three require direct interaction with the tools; in other words, you cannot become proficient by simply reading books on the topics. In this chapter, your students will begin acquiring a fundamental knowledge of C++ by learning about data types, functions, identifiers, assignment statements, arithmetic operations, and input/output operations.  They will then write and test programs using these concepts to verify their knowledge of the material.
·          
·          

Objectives


In this chapter, the student will:
·         Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers
·         Explore simple data types
·         Discover how to use arithmetic operators
·         Examine how a program evaluates arithmetic expressions
·         Learn what an assignment statement is and what it does
·         Become familiar with the string data type
·         Discover how to input data into memory using input statements
·         Become familiar with the use of increment and decrement operators
·         Examine ways to output results using output statements
·         Learn how to use preprocessor directives and why they are necessary
·         Explore how to properly structure a program, including using comments to document a program
·         Learn how to write a C++ program
·          

Teaching Tips


The Basics of a C++ Program
·          
1.      Introduce this chapter by explaining that a C++ program is essentially a collection of one or more subprograms, called functions. Note that although many functions are predefined in the C++ library, programmers must learn how to write their own functions to accomplish specific tasks.
·          
2.      Emphasize that every C++ program must have a function called main. Use Example 2-1 to illustrate a basic main function.
·          
3.      Define the terms syntax rules and semantic rules as they relate to a programming language and explain the difference between the two.
·          

Teaching

Tip

Emphasize that compilers check for syntax but not semantic errors. Give an example of each type of error.
·          
·          
·         Comments
·          
1.      Use the program in Example 2-1 to describe the use and importance of comments. Stress that comments are for the reader, not for the compiler.
·          
·         Special Symbols
·          
1.      Explain that the C++ programming language consists of individual units called tokens, and these are divided into special symbols, word symbols, and identifiers.
·          
2.      Go over some of the special symbols in C++, including mathematical symbols, punctuation marks, the blank symbol, and double characters that are regarded as a single symbol.
·          
·         Reserved Words (Keywords)
·          
1.      Discuss the word symbols, or keywords, used in C++, using Appendix A as a guide.  Emphasize that C++ keywords are reserved and cannot be redefined for any other purpose with a program. 
·          
·         Identifiers
·          
1.      Define the term identifier as a name for something, such as a variable, constant, or function. 
·          
2.      Discuss the rules for naming identifiers in C++. Also note that C++ is a case-sensitive language.
·          

Teaching

Tip

Discuss the difference between C++ conventions and rules. For example, it is a rule that a mathematical symbol cannot be used in an identifier name. However, it is a convention to begin an identifier with a lowercase letter.
·          
·          
·         Whitespaces
·          
1.      Explain that whitespaces (which include blanks, tabs, and newline characters) are used to separate special symbols, reserved words, and identifiers.
·          
          
Data Types
·          
1.      Explain that C++ categorizes data into different types in order to manipulate the data in a program correctly. Although it may seem cumbersome at first to be so type-conscious, emphasize that C++ has these built-in checks to guard against errors.
·          

Teaching

Tip

Explain that C++ is called a strongly-typed language because it checks for operations between inconsistent data types. This results in more robust and error-free programs. Demonstrate how C++ checks for data types with a simple program that attempts to add a string and a numeric value.
   
·          
2.      Mention that C++ data types fall into three categories: simple data types, structured data types, and pointers. Only the first type is discussed in this chapter.   
·          
·         Simple Data Types
·         
1.      Using Figure 2-2, describe the three categories of simple data types in C++: integral, floating-point, and enumeration.
·           
2.      Using Figure 2-3, mention the nine categories of integral data types. Explain why C++   (and many other languages) has so many categories of the same data type. In addition, discuss the rules involving the use of integral types.
·          
3.      Explain the purpose of the bool data type.
·          
4.      Discuss the char data type, including its primary uses. Mention commonly used ASCII characters and their predefined ordering. Explain that a char data type is enclosed in single quotation marks, and note that only one symbol may be designated as a character.
·          
·         Floating-Point Data Types
·          
1.      Use Table 2-3 to explain how C++ represents real, or floating-point, numbers. Use Figure 2-4 to mention the three categories of data types to represent real numbers (float, double, and long double), and explain when to use each type.
·          
2.      Define the terms precision, single precision, and double precision.
·          

Teaching

Tip

Demonstrate how to find the values of float and double on a particular system by running the program with the header file in Appendix F. Encourage students to try running this program on their own computers and comparing the results.
·          
·          
·          


·       Quick Quiz 1
·          
  1. What is an enumeration type?
·         Answer: C++’s method for allowing programmers to create their own simple data types
·          
  1. The maximum number of significant digits in a number is called the ____________________.
·         Answer: precision
·          
3.      The data type ____________________ has only two values: true and false.
·                    Answer: bool
·          
  1. The ____________________ data type, the smallest integral data type, is used to represent integral numbers between -128 and 127.
·                    Answer: char
·          
·          
Arithmetic Operators and Operator Precedence
·          
1.      Discuss the five arithmetic operators in C++ that are used to manipulate integral and floating-type data types.
·          
2.      Explain the difference between unary and binary operators.
·          
·         Order of Precedence
·          
1.      Review operator precedence rules, as C++ uses these rules when evaluating expressions. Example 2-5 illustrates the use of parentheses to override the order of operator precedence.
·          
·          
Expressions
·          
1.      This section discusses integral and floating-point expressions in detail. Use Examples 2-6 and 2-7 to clarify how C++ processes expressions.

Mixed Expressions

1.      Discuss the two rules for evaluating mixed expressions and illustrate these rules in practice using Example 2-8.........
















Free tutorial : Basic Elements of C++



1

Download PDF : Arrays


Download PDF : Arrays
Download PDF : Arrays







Introduction
An array is a collection data that has homogeneous type. It is stored in memory and, in C++, is accessed directly from memory, which is one reason for the efficiency the use of arrays in a program, and is one reason for the attendant dangers. Most machine architectures have facilities to access memory in exactly the way that C++ calculates the addresses of its array members through indexing. The C++ compiler can issue machine language instructions that directly implement C++ array commands without a lot of supporting instructions as is needed in a language where the access is less direct and more strongly protected.
1. Outline of topics in the chapter
5.1 Introduction to Arrays
Declaring and Referencing Arrays
Arrays in Memory
Initializing Arrays

5.2 Arrays in functions
Indexed Variables as Function Arguments
Entire Arrays as Function Arguments
The const Parameter modifier
Functions That Return an Array
Example: Production Graph

5.3 Programming with Arrays
Multidimensional Array Basics
Multidimensional Array Parameters

2. General remarks on the chapter
Students who come to C++ from Java will be concerned to find that the array is not an object, and has none of the member functions nor any protection against misuse that the Java array has. Students that come to C++ from some more protective language such as Pascal will find the low level, non-protective C/C++ array notion to be a concern at the least. I will give some of the concerns, and a bit of the reasoning behind them. I usually discuss these ideas in my presentation of the array concept.
5.1 Introduction to Arrays
C++ has adopted the (low-level) C notion of array without change.  In C++ the notion of array is quite 'low level'. By this I mean that in C++, arrays, along with pointers and the notion of conversion of an array to a pointer, provide a mechanism that closely models memory and address concepts in traditional computer hardware. The concept is both simple and general, and has the potential to be quite efficient -- and, in careless hands, it is quite dangerous.

We have said that the C++ array mechanism provides no protection against abuse and error. Ellis and Stroustrup (ARM page 137) point out the low-level nature of C++ arrays result in the following major limitations:

1) An array is of fixed size, with the size specified at compile time.
2) An array is one-dimensional. Multidimensional arrays in C/C++ are arrays of base type arrays.
3) An array is not self-describing. Given a pointer to an array, there is no information to determine the size of an array.

This last property means that passing an array as a function parameter is inherently dangerous. The array type deteriorates into a pointer when passed as a function parameter. This implies that a separate size parameter must be provided for safety if a function is to have an array argument.

If any of the properties mentioned are a problem in programming, the C++ programmer always has the option to create an ADT by embedding the array in a class. This class could overload the [] operator and provide array bounds checking, variable array size, or otherwise addresses the above properties that are seen as shortcomings in a given setting.
Declaring and Referencing Arrays
Be careful with the terminology. The text points out that there is much terminology, and it varies greatly. The problems will usually be with students who have some programming experience, but not enough to allow them to be comfortable with a change in the words used to describe these ideas.

A particular problem that my Pascal refugees have is that Pascal provides the start and ending array indices, both extremes of which are usable. Unless a programming problem calls for an array to start at some value other than 1, the Pascal arrays traditionally start at 1 and run to the given size.  On the other hand, C/C++ arrays always run from 0 to one less than the array size. The starting index is not mentioned in the declaration, and the number that is mentioned, the size of the array, is not a usable index.

A difficulty Java students have is caused by the fact that Java arrays have member functions. I have seen students who know Java well, when asked to write a low-level stand-alone copy function for arrays use the array as if it were a Java array or a C++ vector.

My students tend to confuse the use of the [] in x[4] in a declaration, as in int x[4]; with the use of the [] in x[3] in an access to the array. I think the problem should be mentioned to your classes. The text discusses this at the top of page 173. In x[4] the [] are technically array declarators. In x[3] the [] are the index operator

Arrays in Memory
As mentioned in the opening paragraph, C/C++ arrays do not provide array bounds checking. If an index outside the array bounds is used, strange results may occur. Unfortunately, out of bounds array index use is not guaranteed to cause a problem. If an MS DOS, Windows 9x (includes Me), or pre-OS-X Mac platform is used, there is significant potential for hanging the machine by overwriting an important address that belongs to the operating system.

Better protection is promised in the latest Macintosh operating system (OS-X) and Windows 2000 and XP. I can’t speak about the Mac as I have never used one. I have done some programming under Windows NT and 2000. These are more stable platforms than Windows 9x. However, Windows 9x is sufficiently unstable that I cannot recommend it for any programming. Windows 9x still tends to behave really strangely when a C++ application uses out of bounds array indices. Be careful. There be dragons. Reboot often.

You will hear students say that "with a bad write to memory, you can cause the hard disk to be reformatted." This isn't going to happen. My students appreciate being told this comforting bit of information. Most PCs today have EIDE controllers. These controllers do not have the capability to low-level format a hard disk without a utility from the manufacturer. The few SCSI controllers that exist in PCs may have disk utilities in ROM that could format a disk. It may be possible for inadvertent write to specific addresses to possibly start this menu on a machine with an operating system that does not protect memory. This is in fact unlikely, and if it did happen, it is unlikely to cause mischief.

Some operating systems run in a mode called protected memory mode. Such machines may be Suns or other Unix machines, machines running Linux, some version of BSD, NT or successor, or one of the (few) other fully protected mode operating systems. In these operating systems a physical address on an interface card cannot be reached. In these operating systems, the worst that can happen when array index is very far out-of-bounds is that a run time error can occur. These are reported on Linux system as a segmentation violation. Note that Microsoft Windows 9x and Me do not protect against much of anything. They crash in ways that are mysterious, some even make rebooting difficult.

Sun, HP, VAX, and other workstations run fully protected mode operating systems, usually a Unix variant or a NT or successor.

Finally, an understanding of what happens when you index into an array based on the memory model presented in the text (Display 5.2, page 178) is of great importance. 

Initializing Arrays
In initializing an array,
  int children[3] = {1, 12, 1};
the number of initializers must be no greater than the declared size of the array. There can be fewer initializer. In such an event the first array entries will be initialized from the list, the C++ Standard says the arrays are to be initialized to a zero appropriate to the type. Note that this is true even for primitive types and for class types, where the default constructor is used for the “zero of appropriate type.”  However, if there are no initializers, and the base type is primitive, the array is not initialized all. If the base array type is a class type, if there are no initializers, the default constructor is called for each array item. At least this is what the C++ Standard says, and all three of my compilers seem to do this. (Specifically, I have tried this on Linux and g++-2.9.5 and g++-3.0, Borland 5.0 IDE, Borland’s command line compiler 5.5, and VC++ 6.0).

5.2 Arrays in functions
Here the student must do the self-test exercises, and make up her own exercises. The code fragments should be tested by embedding them in small programs as suggested in the exercises. This stuff isn't difficult, but it does require substantial exposure over a period of time to internalize the ideas....

















Download PDF : Arrays

0