Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Stepping Up To C++


February 1995/Stepping Up To C++

Stepping Up To C++

Minor Enhancements to C++ as of CD Registration

Dan Saks


Dan Saks is the president of Saks & Associates, which offers consulting and training in C++ and C. He is secretary of the ANSI and ISO C++ committees. Dan is coauthor of C++ Programming Guidelines, and codeveloper of the Plum Hall Validation Suite for C++ (both with Thomas Plum). You can reach him at 393 Leander Dr., Springfield OH, 45504-4906, by phone at (513)324-3601, or electronically at [email protected].

In July, the ANSI and ISO C++ standards committees voted to submit their working draft of the C++ standard for registration as a CD (committee draft). This is the second installment in a series that summarizes the state of the C++ language as of that milestone.

Since adopting the ARM [1] as the base document for the standard, the committees have done a lot more than just clarify the C++ language definition; they have been changing existing features and adding new ones at a fairly steady clip. CD registration represents, among other things, a tacit statement from the committees that they're more or less done adding new stuff. The words in the draft are not yet as clear or as precise as they will be when the standard is final, but at least now the draft describes most, if not all, of the language features we should expect to see in that eventual C++ standard.

Last month, I listed all of the ways the C++ language described by the draft standard differs from the dialect described in the ARM. (See "Stepping Up to C++: C++ at CD Registration," CUJ, January 1995.) My list included only substantive changes (changes in the C++ language itself) and omitted changes that are essentially editorial (changes in the description of C++, not in C++ itself).

I classified the substantive changes into four broad categories:

  • major extensions that dramatically increase the complexity of the language and support alternative programming styles and paradigms
  • minor enhancements that extend the language in less dramatic ways
  • changes that alter the meaning of existing features
  • clarifications of existing features
I also provided brief explanations of each of the major extensions:

  • templates
  • exception handling
  • run-time type information (including dynamic_cast)
  • namespaces
along with pointers to other sources of information about these features.

This month, I continue in the same vein with explanations of the minor enhancements. Some of these review features I described in earlier columns. (See "Stepping Up To C++: Recent Extensions to C++," CUJ, June, 1993, and "Stepping Up To C++: The Return Type of Virtual Functions," CUJ, March, 1994.) Stroustrup [2] offers more insights and examples on most of these features.

New Keywords and Digraphs

C++, like C, requires a character set based on the Roman alphabet. In particular, C++ uses the English alphabetic characters 'A' through 'Z' and 'a' through 'z', along with a handful of arithmetic operators and punctuation symbols. Unfortunately, many other natural languages based on the Roman alphabet use more than just the 26 (times two) characters in the English alphabet.

Computer systems that support non-English alphabets usually make room for native language characters and punctuation by omitting other punctuation characters normally found on American English systems. For example, Danish keyboards, displays, and printers replace the [ and ] with and , respectively. A subscript expression like a[i] comes out on a Danish display device looking like ai. I can imagine that this takes some of the fun out of programming in C and C++.

ISO646 is the international standard 7-bit character set. It specifies the set of characters common to all systems based on the Roman alphabet. ISO646 does not use every available 7-bit code. Each nationality can define its own variant of ISO646 that uses the unused codes for native language characters or symbols. ASCII, the US national variant of ISO646, uses the available codes for symbols like {, }, [, ], /, ^, \, and ~ (all of which are used in C and C++). Other national variants assign these same codes to other alphabetic characters, like or , or to punctuation like .

A current trend in international standards is to augment programming languages so that programmers can work without too much inconvenience using only the invariant set of ISO646 characters. As part of this trend, C++ includes new keywords and digraphs (two-character symbols) as alternate ISO646-compliant spellings for the troublesome operators. These keywords and digraphs appear in Table 1. Using the digraphs, you can write the subscripting expression a[i] as a<:i:>.

ISO C provides the same alternate spellings; however, C specifies the identifiers in Table 1 as macros defined in a standard header <iso646.h>. Thus, you can continue using those identifiers as user-defined identifiers in C as long as you don't include <iso646.h>. However, C++ treats these identifiers as reserved words; you cannot use them as user-defined identifiers in any C++ program. The C++ library provides a header <iso646.h> (which may be empty) just for compatibility with C.

Operator Overloading on Enumerations

At one time, enumerations were integral types (as they are in C), but those days are gone. The current draft says that each distinct enumeration constitutes a different enumerated type. Enumerations are not integral, but they do promote to int, unsigned int, long, or unsigned long.

For example, given

enum day { SUN, MON, ..., SAT };
a valid C declaration like

enum day d = 0;
is no longer valid in C++, because C++ won't convert 0 (an int) to day (an enumeration) without a cast. However,

int n = SUN;
is still valid in C++, as it is in C, because SUN (a constant of type day) still promotes to int.

C++ does not allow operator overloading on primitive types, such as int. When enumerations were integral types, C++ could not allow operator overloading on enumerations either, without severely complicating the rules for overload resolution. Once enumerations became distinct types, allowing overloading on enumerations became a relatively small change.

Removing enumerations from the integral types introduced a potentially serious incompatibility with C, namely, that various built-in arithmetic operators, such as ++, , += and -=, no longer apply to enumerations. Therefore, a loop such as

for (d = SUN; d <= SAT; ++d)
no longer compiles as C++ when ++ is the predefined operator. However, with operator overloading on enumerations, you can define

inline day &operator++(day &d)
   {
   return d = day(d + 1);
   }
as the prefix form of ++ for objects of type day. With this function definition present, the for statement will compile.

operator new[] and operator delete[]

A new expression acquires storage by calling an allocation function. The standard C++ library provides a default allocation function, declared as

void *operator new(size_t n);
An expression such as

px = new X;
loosely translates into code of the form

px = (X *)operator new(sizeof(X));
px->X();    // apply constructor
A delete expression releases storage by calling a deallocation function. The default deallocation function declared in the library has the form

void operator delete(void *p);
An expression such as

delete px;
loosely translates into code of the form

px->~X();  // apply destructor
operator delete(px);
The default allocation and deallocation functions are very general, and may waste too much time or storage in some applications. C++ lets you write you own versions of operator new and operator delete. If you define your own operator new, every new expression in your program will call your allocator instead of the default supplied in the library. Ditto for operator delete and delete expressions.

Writing replacements for the global allocator and deallocator can be a big chore, and it's usually unnecessary. Often all you need to do is tune the memory allocator for objects of a few particular classes. C++ lets you define a different allocator and deallocator for each class. For example,

class node
   {
public:
   void *operator new(size_t);
   void operator delete(void *p);
   ...
   };
defines class node with its own class-specific versions of new and delete. A call such as

p = new node;
allocates memory using node::operator new, rather than the global operator new. Similarly,

delete p;
deallocates memory using node::operator delete. new and delete expressions for objects of built-in types, and for class types that do not declare their own operator new and operator delete, continue to use the global allocation and deallocation functions.

According to the ARM, allocating an array of X objects always uses the global operator new, even if X is a class that defines its own operator new. That is,

px = new X[n];
ignores X::operator new and uses ::operator new. By the same token, deleting that array using

delete [] px;
ignores X::operator delete and uses ::operator delete.

The current C++ draft standard gives programmers greater control over dynamic memory management for arrays of objects. Now, a new expression such as

px = new X[n];
invokes an allocation function declared as

void *operator new[](size_t n);
Similarly,

delete [] px;
invokes a deallocation function declared as

void operator delete[](void *p);
The standard library provides default implementations for operator new[] and operator delete[], which you can replace at your pleasure. You can even define operators new[] and delete[] for individual classes, as in

class node
   {
 public:
   void *operator new(size_t);
   void *operator new[](size_t);
   void operator delete(void *p);
   void operator delete[](void *p);
   ...
   };
so that

p = new node[n];
invokes node::operator new[] instead of node::operator new.

Relaxed Virtual Function Return Typ es

Quoth the ARM: "It is an error for a derived class function to differ from a base class virtual function in the return type only." For example, in

class B
   {
public:
   virtual int vf(int);
   ...};
class D : public B
   {
   ...
   void vf(int); // error
   ...
};
the declaration of D::vf is an error because it has the same name and signature (parameter types) as a function declared in base class B, but they have different return types. Most of the time, this is a reasonable restriction. Occasionally it isn't. Here's one such occasion.

Some applications need to be able to clone (create an exact copy of) an object. Typically, a cloning function for a class X looks something like

X *X::clone() const
   {
   return new X(*this);
   }
The expression new X(*this) creates a new dynamically-allocated X object by copying the object addressed by this.

When used in a class that's the root of a polymorphic hierarchy, clone functions should be virtual (possibly pure), so you can clone an object without knowing its exact type. For example, Listing 1 shows a simple hierarchy of geometric shapes with a virtual clone function. Using these types, a call such as

shape *cs = s->clone();
creates a new shape with the same dynamic type as shape s. That is, if at the time of the call, s actually points to a circle, then s->clone() returns a circle *. If s points to a rectangle, then s->clone() returns a rectangle *.

Normally, a clone function for a class X should have a return type of X *. However, in Listing 1, circle::clone returns a shape *, not a circle *, to satisfy the ARM's restriction that an overriding function must return exactly the same type as the function it overrides. Unfortunately, satisfying this restriction often requires you to use casts in contexts where it seems that you should not need them. For example, you cannot write

rectangle *r;
...
rectangle *cr = r->clone();
because r->clone() returns a shape *, not a rectangle *. Even though a rectangle is a shape, a shape is not necessarily a rectangle. Therefore, you must add a cast, as in

rectangle *cr = (rectangle *)r->clone();
The current draft relaxes the ARM's original restriction to eliminate the need for this cast. You can declare each virtual clone function in the hierarchy so that it returns a pointer whose static type is the same as its dynamic type. That is, circle::clone can return a circle * and rectangle::clone can return a rectangle *, even though the function they override, shape::clone, returns a shape *.

By and large, the ARM's restriction still stands. The current draft simply adds two special cases where the return types need not match exactly. Specifically, for all classes B and D defined as

class B
   {
   ...
   virtual BT f();
   ...
   };
class D : public B
   {
   ...
   DT f();
   ...
   };
types BT and DT must be identical, or they must satisfy either of the following conditions:

1. BT is BB * and DT is DD *, where DD is derived from BB.

2. BT is BB & and DT is DD &, where DD is derived from BB.

In either case (1) or (2),

3. class D must have the access rights to convert a BB * (or BB &) to a DD * (or DD &, respectively).

In most applications with hierarchies like this, BB is a public base class of DD, so D can perform the conversions. But if, for example, BB is a private base class of DD, then condition (3) does not hold. The above rules apply even if D is derived indirectly from B. Furthermore, BB might be B and DD might be D, as is the case with clone functions.

Types BB and DD, above, may include cv-qualifiers (const and volatile). These qualifiers in BB and DD need not be identical, as long as every qualifier that's part of DD is also part of BB. BB may have qualifiers that are not part of DD.

wchar_t as a Distinct Type

Like C, C++ provides wide-character literals and multibyte strings so that programmers can manipulate very large character sets, like Japanese Kanji. Several headers in the Standard C library define wchar_t as the wide character type, an integral type sufficiently large to represent all character codes in the largest character set among the supported locales.

The C++ committees wanted to support input/output for wide characters as well as "narrow" characters. For example, for a time they wanted to be able to add another output operator

ostream &operator<<(ostream &os,
                wchar_t w);
in addition to existing operators, such as

ostream &operator<<(ostream &os,
                char c);
ostream &operator<<(ostream &os,
                int i);
                //and many others
so that given

int i;
wchar_t w;
the expression

cout << i;
displays i as an int, and

cout << w;
displays w in its proper graphic representation. Unfortunately, this was impossible with wchar_t defined by a typedef.

The problem is that a typedef is not a distinct type; it's an alias for another type. If the library defines wchar_t as

typedef wchar_t int;
then

ostream &operator<<(ostream &os,
                int i);
ostream &operator<<(ostream &os,
                wchar_t w);
are the same function. That function will (most likely) display objects of type wchar_t as numbers.

Thus, wchar_t is now a keyword in C++ representing a distinct type. wchar_t still has the same representation as one of the standard integral types (meaning it has the same size, alignment requirements, and "signedness" as one of the integral types), but it is now a distinct type for the purposes of overload resolution.

A Built-in Boolean Type

C doesn't have a Boolean type; it simply assumes that a scalar value is "false" if it compares equal to zero and "true" if it's non-zero. For the most part, the Standard C library uses int as the Boolean type, and many programmers follow suit.

Those of us who truly felt the absence of a Boolean type defined one ourselves. Unfortunately, there are an awful lot of different ways to do it. Some programmers spell the type as bool. Others use Bool, boolean, Boolean, bool_t, or even logical. The type can be char or int, signed or unsigned. The definition itself can be a macro

#define bool int
#define false 0
#define true 1
or a typedef

typedef unsigned char bool;
or even an enumeration

enum bool { false, true };
Consequently, it's not at all uncommon for the definitions of bool, false, and true (however you spell them) in one library to conflict with the definitions in another.

The C++ standards committees decided to eliminate these conflicts by defining a standard Boolean type. C++ now has a Boolean type with the following properties:

  • bool is a keyword designating a signed integral type.
  • false and true are keywords designating constants of type bool.
  • bool expressions promote to int such that false converts to zero and true converts to one.
  • int and pointer expressions can convert to bool such that zero converts to false and non-zero converts to true.
In addition:

  • The built-in relational operators <, >, ==, !=, <=, and >= yield a bool result.
  • The built-in logical operators &&, //, and ! take bool operands (or operands that automatically convert to bool) and yield a bool result.
  • The conditional expression in an if, while, or for statement, or the first operand of ?:, must have bool type (or a type that automatically converts to bool).
The committees' intent is that, except for definitions of bool, false, and true, code that uses a Boolean type should continue to work as before.

The committees agreed to preserve, at least for the time being, the sloppy but apparently common coding practice of using ++ to set a Boolean value to true. C++ currently accepts prefix and postfix ++ as lvalue, of type bool, both of which set to true. However, the draft deprecates this feature, meaning it may disappear from some future standard.

By the way, the committees did explore alternatives to defining bool as a built-in type. They considered defining it in the library as a typedef, as a class, or as an enumeration, but each approach had flaws.

The problem with a typedef is that it is not a distinct type for overloading. If the library defines

typedef int bool;
then declarations

void f(int);
void f(bool);
are not a pair of overloaded functions; they're two declarations for the same function. (This is the same reason why wchar_t is not a typedef.)

Defining bool as a class type poses a different problem. Given the current rules for applying user-defined conversions during argument-matching, defining bool as a class might break existing code. In their analysis of the Boolean type, Dag Brck and Andrew Koenig used an example similar to the one in Listing 2 to illustrate the problem.

Listing 1 shows a class X with a constructor that accepts a single int argument. Thus, that constructor is also a user-defined conversion from int to X. In the absence of a bool type, the expression n > 0 yields an int. The call f(n > 0) uses the constructor X(int) to convert that int result to X, and then passes that X to f(X).

Now suppose C++ defined bool as a class type with a conversion to int:

class bool
   {
public:
   operator int();
   ...
   };
If relational operators, like >, yield a bool result, then the call f(n > 0) in Listing 2 must first convert the result of n > 0 to int using bool::operator int, and then convert that int to X using X::X(int). Unfortunately, there's already a rule in C++ that argument matching during a function call will apply at most one user-defined conversion. When bool is a class, this call requires two user-defined conversions: bool::operator int and X::X(int). Brck and Koenig reasoned that to avoid breaking this code or meddling with the already complicated argument-matching rules, the conversion from bool to int cannot be user-defined; it must be built-in.

When enumerations were still integral types, it might have been possible to define bool as an enumeration and preserve the implicit conversions from int to bool. Since int values no longer convert quietly to enumerations, it can't be done without special rules for bool. But that's the same as making bool a built-in type.

Declarations in Conditional Expressions

The proposal to add run-time type information (RTTI) included an extension to allow declarations in conditional expressions. The scope of a name declared in a condition is the statement(s) controlled by that condition. For example,

if (circle *c = dynamic_cast<circle *>(s))
   {
   // c is in scope here...
   }
// but not here
The declaration yields the value of the declared object after initialization.

The syntax for such declarations is extremely limited. (The revised grammar appears in Table 2. ) The declaration can declare only one object, and it must have an initializer with = as the delimiter. For example, C++ will not accept

if (complex z(r, i))
You must write the condition as

if (complex z = complex(r, i))
Declarations can appear in place of expressions only in the controlling expressions of if, switch, for, or while statements. They cannot appear in the increment expression of a for statement, in the controlling expression of a do-while statement, or in the conditional expression of ?: expression.

The scope of a name declared in the condition of an if statement includes the else part. For example,

if (int c = getchar())
   {
   // c is non-zero here
   }
else
   {
   // c is zero here
   }
//c is undefined here
Finally, you cannot declare an entity in the outermost block of the statement controlled by a condition using the same name as the object declared in the condition. For example,

while (X *p = iter.next())
   {
   char *p;    // error, p already declared
   ...
   }
I'll continue next month with the explanations of the other minor enhancements to C++.

References

[1] Margaret A. Ellis and Bjarne Stroustrup. The Annotated C++ Reference Manual. (Addison-Wesley, 1990).

[2] Bjarne Stroustrup. The Design and Evolution of C++. (Addison-Wesley, 1994).


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.