Keywords

Chapter 5 - C and C++ Programming

Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
  Copyright 1998 The McGraw-Hill Companies

C++ Archives
Not surprisingly, C++ has an origin similar to C’s. While C++ is somewhat like BCPL and Algol 60, it also contains components of Simula 67. C++’s ability to overload operators and its flexibility to include declarations close to their first point of application are features found in Algol 60. The concept of subclasses (or derived classes) and virtual functions is taken from Simula 67. Like many other popular programming languages, C++ represents an evolution and refinement of some of the best features of previous languages. Of course, it is closest to C.
Bjarne Stroustrup, of Bell Labs, is credited with developing the C++ language in the early 1980s. (Dr. Stroustrup credits Rick Mascitti with the naming of this new language.) C++ was originally developed to solve some very rigorous event-driven simulations for which considerations of efficiency precluded the use of other languages. C++ was first used outside Dr. Stroustrup’s language group in 1983, and by the summer of 1987, the language was still going through a natural refinement and evolution.
One key design goal of C++ was to maintain compatibility with C. The idea was to preserve the integrity of millions of lines of previously written and debugged C code, the integrity of many existing C libraries, and the usefulness of previously developed C tools. Because of the high degree of success in achieving this goal, many programmers find the transition to C++ much simpler than when they first went from some other language, such as FORTRAN, to C.
C++ supports large-scale software development. Because it includes increased type checking, many of the side effects experienced when writing loosely typed C applications are no longer possible.
The most significant enhancement of the C++ language is its support for object- oriented programming (OOP). You will have to modify your approach to problem solving to derive all of the benefits of C++. For example, objects and their associated operations must be identified and all necessary classes and subclasses must be constructed.
Object Code Efficiency
What follows is an example of how an abstract data object in C++ can improve upon an older language’s limited built-in constructs and features. For example, a FORTRAN software engineer may want to keep records on students. You could accomplish this with multiple arrays of scalar data that represent each set of data. All of the arrays are necessarily tied together by a common index. Should there be ten fields of information on each student, ten array accesses would have to be made using the same index location in order to represent the array of records.
In C++, the solution involves the declaration of a simple object, student_database, that can receive messages to add_student, delete_student, access_student, or display_student information contained within the object. The manipulation of the student_database object can then be performed in a natural manner. Inserting a new record into the student_database object becomes as simple as this:
student_database.add_student(new_recruit)
Assuming the student_database object has been appropriately declared, the add_student( ) function is a method suitably defined in the class that supports student_database objects, and the new_recruit parameter is the specific information that is to be added. Note that the class of objects called student_database is not a part of the underlying language itself. Instead, the programmer extends the language to suit the problem. By defining a new class of objects or by modifying existing classes (creating a subclass), a more natural mapping from the problem space to the program space (or solution space) occurs. The biggest challenge comes in truly mastering this powerful enhancement.
Subtle Differences Between C and C++
The following sections detail the minor (non-object-oriented) enhancements to the C language.
Comment Syntax
C++ introduces the comment to end-of-line delimiter //. However, the comment brackets /* and */ can still be used.
Enumerated Variables
The name of an enumeration is a type name. This streamlines the notation by not requiring the qualifier enum to be placed in front of the enumeration type name.
Structure Versus Classes
The name of a structure or class is a type name. This class construct does not exist in C. In C++, it is not necessary to use the qualifier struct or class in front of a structure or class name.
Block Scope
C++ permits declarations within blocks and after code statements. This feature allows you to declare an identifier closer to its first point of application. It even permits the loop control variable to be declared within the formal definition of the control structure, as shown here:
// C++ point-of-use variable declaration
  for(int index = 0; index < MAX_ROWS; index++)
Scope Resolution Operator
You use the new scope qualifier operator :: to resolve name conflicts. For example, if a function has a local declaration for a variable vector_location and there exists a global variable vector_location, the qualifier ::vector_location allows the global variable to be accessed within the scope of the local function. The reverse is not possible.
The const Specifier
You can use the const specifier to lock the value of an entity within its scope. You can also use it to lock the data pointed to by a pointer variable, the value of the pointer address, or the values of both the pointer address and the data pointed to.
Anonymous Unions
Unions without a name can be defined anywhere a variable or field can be defined. You can use this ability for the economy of memory storage by allowing the sharing of memory among two or more fields of a structure.
Explicit Type Conversions
You can use the name of a predefined type or user-defined type as a function to convert data from one type to another. Under certain circumstances, such an explicit type conversion can be used as an alternative to a cast conversion.
Unique Function Capabilities
C++ will please many a Pascal, Modula-2, and Ada programmer because it permits the specification by name and type for each function parameter inside the parentheses next to the function name. For example:
void * dupmem(void *dest, int c, unsigned count)
{
 .
 .
 .
}
The equivalent C interface, under the ANSI standard, would look exactly the same. In this case, C++ influenced the ANSI standards committee.
The C++ translator will perform type checking to ensure that the number and type of values sent into a function when it is invoked match the number and type of the formal arguments defined for the function. A check is also made to ensure that the function’s return type matches the variable used in the expression invoking the function. This type of parameter checking is missing in most C systems.
Overloading Functions
In C++, functions can use the same names if you use the specifier overload, and each of the overloaded functions can be distinguished on the basis of the number and type of its parameters.
Default Parameter Values
You can assign default values to trailing sets of C++ function parameters. In this case, the function can be invoked using fewer than the total number of parameters. Any missing trailing parameters assume their default values.
Varying-Length Argument Lists
You can define C++ functions with an unknown number and type of parameters by employing the ellipsis (...). When you use this feature, parameter type checking is suppressed to allow flexibility in the interface to the function.
Reference Argument Types
Through the use of the ampersand operator (&), a formal function parameter can be declared as a reference parameter. For example:
int i;
increment(i);
 .
 .
 .

void increment(int &variable_reference)
{
 variable_reference++;
}
Because &variable_reference is defined as a reference parameter, its address is assigned to the address of i when increment( ) is invoked. The value of i that is sent in is incremented within function increment( ) and returned to variable i outside of function increment( ). It is not necessary for the address of i to be explicitly passed into function increment( ), as it is in C.
Inline Functions!
You can use the inline specifier to instruct the compiler to perform inline substitution of a given function at the location where the function is invoked.
The new and delete Keywords
The new and delete operators that are introduced by C++ allow for programmer-controlled allocation and deallocation of heap storage.
void Pointers
In C++, the type void is used to indicate that a function returns nothing. Pointer variables can be declared to point to void. They can then be assigned to any other pointer that points to an arbitrary base type.
Major Differences Between C and C++
The most significant major enhancement to C involves the concept of object-oriented programming. The following sections briefly explain all of the C++ enhancements that make object-oriented programming possible.
Class Constructs and Data Encapsulation
The class construct is the fundamental vehicle for object-oriented programming. A class definition can encapsulate all of the data declarations, the initial values, and the set of operations (called methods) for data abstraction. Objects can be declared to be of a given class, and messages can be sent to objects. Additionally, each object of a specified class can contain its own private and public sets of data representative of that class.
The struct Class
A structure in C++ is a subset of a class definition and has no private or protected sections. This subclass can contain both data (as is expected in ANSI C) and functions.
Constructors and Destructors
Constructor and destructor methods are used to guarantee the initialization of the data defined within an object of a specified class. When an object is declared, the specified initialization constructor is activated. Destructors automatically deallocate storage for the associated object when the scope in which the object is declared is exited.
Messages
As you have seen, the object is the basic fabric of OOP. You manipulate objects by sending them messages. You send messages to objects (variables declared to be of a given class) by using a mechanism similar to invoking a function. The set of possible messages that can be sent to an object is specified in the class description for the object. Each object responds to a message by determining an appropriate action to take based on the nature of the message. For example, if Palette_Colors represents an object, and SetNumColors_Method represents a method with a single-integer parameter, sending a message to the object would be accomplished by using the following statement:
Palette_Colors.SetNumColors_Method(16);
Friends
The concept of data hiding and data encapsulation implies a denied access to the inner structures that make up an object. The class’ private section is normally totally off-limits to any function outside the class. C++ does allow other functions outside methods or classes to be declared to be a friend to a specified class. Friendship breaks down a normally impenetrable wall and permits access to the class’ private data and methods.
Operator Overloading
With C++, the programmer can take the set of predefined operators and functions supplied with the compiler, or user-defined operators and functions, and give them multiple meanings. For example, different functions typically have different names, but for functions performing similar tasks on different types of objects, it is sometimes better to let these functions have the same name. When their argument types are different, the compiler can distinguish them and choose the right function to call. What follows is a coded example; you could have one function called total( ) that was overloaded for an array of integers, of floating points, and of double values.
int total(int isize, int iarray[]);
float total(int isize, float farray[]);
double total(int isize, double darray[]);
   .
   .
   .
Since you have declared the three different functions by the same name, the compiler can look at the invoking statement and automatically decide which function is appropriate for the formal parameter list’s arguments:
 total(isize,iarray);
   total(isize,farray);
....total(isize,darray);
Derived Classes
A derived class can be seen as a subclass of a specified class, thereby forming a hierarchy of abstractions. Derived class objects typically inherit all or some of the methods of the parent class. It is also common for a derived class to then incorporate these inherited methods with new methods specific to the subclass. All subclass objects contain the fields of data from the parent class as well as any of their own private data.
Polymorphism Using Virtual Functions
Polymorphism involves a tree structure of parent classes and their subclasses. Each subclass within this tree can receive one or more messages with the same name. When an object of a class within this tree receives a message, the object determines the particular application of the message that is appropriate for an object of the specified subclass.
Stream Libraries
An additional library stream is included with the C++ language. The three classes cin, cout, and cerr are provided for terminal and file input and output. All of the operators within these three classes can be overloaded within a user-defined class. This capability allows the input and output operations to be easily tailored to an application’s needs.

Books24x7.com, Inc 2000 –  


Visual C++ 6(c) The Complete Reference
Visual Studio 6: The Complete Reference
ISBN: B00007FYGA
EAN: N/A
Year: 1998
Pages: 207

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