HPlogo HP C++ Programmer's Guide: HP 9000 Series Workstations and Servers > Chapter 1 Overview of HP C++

How C++ Differs from C

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

C++ is often described as a superset of C because C++ has many of the features of C, plus some additional features. There are, however, some differences between the two languages aside from the additional features of C++. This section briefly describes the following:

  • Compatibility with C

  • Reliability Improvements

  • Other Extensions to C

  • Changing Your C Programs to C++

C++ also differs from C in its support of object-oriented programming. Refer to "Support for Object-Oriented Programming" for a discussion of C++ as an object-oriented programming language. For more details about the C++ language, refer to the The C++ Programming Language.

Compatibility with C

Retaining compatibility with C served as a major design criterion for C++. The basic syntax and semantics of the two languages are the same. If you are familiar with C, you can program in C++ immediately.

For instance, C++ preserves C's efficient interface to computer hardware. That is, C++ has the same types, operators, and other facilities defined in C that usually correspond directly to computer architecture. You can use these facilities to write code that makes optimal use of the hardware at run time (for example, code that manipulates bits and uses register variables).

C++ also preserves and enhances the C facilities for designing interfaces among program modules. These facilities are extremely useful when you develop any size application, but particularly a large or complex one.

Finally, C++ modules can usually be linked with already existing C modules with few if any modifications to the C files. This means that you can probably use many C libraries with your C++ programs.

Refer to "Changing Your C Programs to C++," in this chapter, for a description of specific things you might want to change in order to convert existing C programs to C++ programs. Refer to Chapter 5 “Inter-Language Communication”, "Inter-Language Communication," for details about linking C programs with C++ programs.

Reliability Improvements

C++ provides several features to help you create more reliable programs. These features include type checking, constant data types, and flexibly located variable declarations. The following sections briefly describe these features.

Type Checking Features in Functions

You declare functions in C++ just as you do in C, except that C++ supports type checking of arguments. Type checking means that the compiling system detects many errors at compile time rather than at run time, so you can correct them earlier in the development process.

Unlike pre-ANSI C functions, C++ functions must specify types for function arguments. Furthermore, the compiling system performs type checking and type conversion. This means that it compares the argument types with the parameter types in a function definition each time the function is called. If the types are not compatible, the compiling system generates an error. For example, suppose you define a function max and then make the function calls shown in the following code fragment:

float max(float x,float y)       // Define a function, max.
{  return (x>y) ? x : y;  }
    .
    .
    .
max (4.0, 9.0);     // This function call will compile since
                    // both arguments are floats.
max(4,9);           // This function call will compile since
                    // the function arguments are integers,
                    // which can be converted to floats.
max("Four",9.0);    // WRONG!
                    // First argument is a character string, which
                    // is an incorrect type, and conversion is not
                    // possible.

C++ provides function argument checking that is compatible with ANSI C. C++ also provides type-safe linkage with checking done at run time, unlike C.

Constant Data Types

C++ provides a new keyword, const, that declares an identifier to be a constant. A similar feature is also part of ANSI C. For example, the following line creates a variable days, which behaves exactly like any other int variable except that its value cannot be changed:

const int days = 7;   // Days is an integer constant.

You can also use const with pointers, either to declare an object pointed to as a constant or to declare the pointer itself as a constant.

You can use a const declaration in a C++ program in many places where you would have used a #define macro in a C program. Unlike constants created by #define macros, which are purely textual substitutions, const values can have type and scope like variables.

Variable Declarations

C++ allows you to declare variables and statements in any order, as long as you declare variables before you use them. You can declare variables almost anywhere in a block, not just at the beginning. As a result, you can locate variables with the statements that use them. For example, the following fragment is legal in C++:

for (int j = 0; j < 100; j++)

The example shows how C++ allows you to declare and initialize the variable j in the for loop statement instead of at the start of the function.

Other Extensions to C

The previous sections describe how C++ can improve reliability. Other features of C++ distinguish it from C. Many of these additional features add to its support for object-oriented programming as well as to its stronger type checking. This section describes these additional features very briefly. Refer to "Support for Object-Oriented Programming" for details about object-oriented programming.

Comments

C++ has the following two notations for comments:

  • Comments can begin with the characters /* and end with */, as they do in C.

  • Any line that begins with // is a comment, and any text following // until the end of the line is a comment.

You can use both styles of notation in the same file.

For example,

/* This is a C-style comment that extends
over more than one line; it is also a
legal comment in C++ */

// This is a C++-only comment that
// extends over more than one line

Here's another example of a C++ comment:

int i; // counter variable

Default Arguments

To account for missing arguments in a function call, function declarations and definitions can specify default expressions for the arguments. You declare these default expressions simply by initializing the arguments. The initialized values are called default values. For instance, the following code fragment shows two default arguments:

// default values are 0 and "none"
void add_items (int i=0, char *str = "none");

When a call to add_items is missing an argument, the default value is substituted in its place. If a call to add_items has two arguments, then the default values are ignored. You can provide default values for trailing arguments only. Trailing arguments are the last arguments in the argument list.

Variable Number of Arguments

In addition to specifying argument types, a C++ function declaration can specify that a variable number of arguments is accepted. This is also a feature of ANSI C.

You declare a function with variable arguments by adding ellipsis points (...) to the end of the declaration of the function's argument list. The ellipsis instructs the compiler to accept any number of actual arguments of any type from that point on in the argument list of a function call. For example, the following function can be called with a variable number of arguments:

int file_print(FILE*, char*, ...);

The preceding code fragment declares that file_print is a function that returns an integer and can be called with a variable number of arguments, the first two of which must be of the types FILE* and char*, respectively.

Overloaded Functions

C++ supports function name overloading, which allows you to give the same name to different functions. You typically use function overloading for functions that perform the same operations on objects of different types. The compiling system determines which function to use based on the number and type of arguments that are passed.

For example, you might want to define two functions named print. One can be used for printing integers and the other for printing character strings. Or you might want to be able to handle information about dates as integers (when you want to do calculations) or as characters (when you want to display them). The following code fragment illustrates a function, handle_date, that handles dates as either integers or characters.

// This function takes three arguments that must be integers.
void handle_date(int day, int month, int year);

// This function takes one argument that must be a pointer
// to a character.
void handle_date(char* date);
NOTE: Releases of the translator before version 2.0 required the use of the keyword overload to specify that a name could be used for more than one function. As of version 2.1, the keyword overload is obsolete.

Changing Your C Programs to C++

This section contains information about changes you might want to incorporate into C programs and header files that you intend to use with HP C++. These changes are in the following categories:

  • new keywords

  • function declarations

  • structures

  • external names

  • constants

  • assignment of void pointers

When you start to use C++ after using C, you might also want to change to an object-oriented approach to programming. Refer to "Support for Object-Oriented Programming" for details about object-oriented programming with C++.

New Keywords

C++ reserves as keywords the following identifiers that are not keywords in HP C:

Table 1-1 C++ Keywords

catchnewthis
classoperatorthrow
const[1]privatetry
deleteprotectedvirtual
friendpublicvolatile[1]
inlinetemplate 

[1] The keywords const and volatile are also keywords in ANSI C.

 

If your C code contains any variables with these names, you must change them when you convert your program to a C++ program.

NOTE: Although it is reserved as a keyword, volatile is not implemented in HP C++. However, the +Ovolatile optimization option makes all global variables volatile, and performs level 2 optimization.

Function Declarations

You should make the following changes involving functions:

  • Explicitly declare all functions. (You cannot use implicit declarations in C++.)

  • Add argument types to function declarations.

  • Use ellipsis points (...) for functions that take varying numbers of arguments.

One important difference between C and C++ is that a C++ function declared as f() takes no arguments, whereas a C function declared as f() can take any number of arguments of any type. This means that you do not need to use void to declare that a C++ function takes no arguments, as you might have done in an ANSI C program.

Unlike ANSI C, C++ does not require a comma separating the ellipsis points from the rest of the argument list when you specify a variable number of arguments.

Structures

Since a C++ struct is a particular form of the class data type, you may need to change your C code to avoid name conflicts.

External Names

In C you can define a variable in an external file more than once. The last initializer read by the linker is the variable's initial value at run time. In C++ you can define a variable declared in an external file exactly once. For example, the following code is legal in C but not in C++:

/* this is a C program but not a C++ program */

#include "file1.c"
#include "file2.c"
extern int foo();
main()
{ 
    .
    .
    .
            }

/* file1.c */
int i ;          /* i is also defined in file2 */
int foo () { return i; }

/* file2.c */
int i;           /* i is also defined in file1 */
int fum() { return foo(); }

If you try to compile this program with CC, you get the following error message:

CC: "file2.c", line 2: error: two definitions of ::i (1034)

In this example, you can eliminate the error generated by CC by specifying the second definition of int i to be extern, as follows:

/* file2 */
extern int i;    /* i is also defined in file1 */
int fum() { return foo(); }

Constants

ANSI C constants are stored as extern, whereas C++ constants are, by default, static, although they can be declared extern. In other words, if you define a file scope const in ANSI C with no storage class (that is, neither static nor extern), the linkage defaults to extern. This is an important difference between types in ANSI C and C++. Hence, the following compiles and links using ANSI C:

/* fileA.c */
const int x = 100;

/* fileB.c */
#include <stdio.h>

main()
{
     extern const int x;
     printf("%d\n", x);
}

These files also compile using HP C++, but fail to link, with the following error:

/bin/ld: unsatisfied symbols
     x (data)

The constant x defined in fileA.c has no "linkage." To make x externally visible, you must explicitly give it the storage class extern, as shown below:

extern const int x = 100;

Assignment of Void Pointers

C++ does not allow you to assign a void pointer to another pointer variable. For instance, the following code is legal in C, but illegal in C++:

char* cp;
void* vp;
cp = vp;          // WRONG!

You must use a cast, as shown below:

cp = (char *) vp;

Character Array Initialization

Character array initialization is handled differently in C++ and ANSI C. For more information refer to The C++ Programming Language.

© Hewlett-Packard Development Company, L.P.