Cplusplus



         


The title given to this article is incorrect due to technical limitations. The correct title is C++.

C++ (pronounced "see plus plus") is a general-purpose computer programming language. It is a statically typed free-form multi-paradigm language supporting procedural programming, data abstraction, object-oriented programming, and generic programming. During the 1990s, C++ became one of the most popular commercial programming languages. No one owns the C++ language and the language is royalty-free.

Bell Labs' Bjarne Stroustrup developed C++ (originally named "C with Classes") during the 1980s as an enhancement to the C programming language. Enhancements started with the addition of classes, followed by, among many features, virtual functions, operator overloading, multiple inheritance, templates, and exception handling. The C++ programming language standard was ratified in 1998 as ISO/IEC 14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003.

[Top]

Technical overview

The 1998 C++ Standard consists of two parts: the Core Language and the Standard Library; the latter includes the Standard Template Library and C's Standard Library. Many C++ libraries exist which are not part of the Standard, such as Boost. Also, non-Standard libraries written in C can generally be used by C++ programs.

[Top]

Features introduced in C++

The C++ language is mainly a superset of C. Features introduced in C++ include declarations as statements, function-like casts, new/delete, bool, reference types, const, inline functions, default arguments, function overloading, namespaces, classes (including all class-related features such as inheritance, member functions, virtual functions, abstract classes, and constructors), operator overloading, templates, the :: operator, exception handling, and run-time type identification.

C++ also performs more type checking than C in several cases.

Comments starting with two slashes ("//") were originally part of C's predecessor, BCPL, and were reintroduced in C++.

Several features of C++ were later adopted by C, including const, inline, declarations in for loops, and C++-style comments (using the // symbol). However, C99 also introduced features that do not exist in C++, such as vararg macros and better handling of arrays as parameters.

[Top]

C++ library

The C++ standard library mostly forms a superset of the C standard library. A large part of the C++ library comprises the Standard Template Library (STL). The STL provides such useful tools as iterators (which resemble high-level pointers) and containers, abstracted data structures (for example arrays, lists, and maps (associative_arrays)) which export compatible interfaces using iterators. As in C, the features of the library are accessed by using the #include directive to include a standard header. C++ provides sixty-nine standard headers, of which nineteen are deprecated.

The STL was originally a third-party library from HP and later SGI, before its incorporation into the C++ standard. The standard does not refer to it as "STL", as it is merely a part of the standard library, but many people still use that term to distinguish it from the rest of the library (input/output streams (IOstreams), internationalization, diagnostics, the C library subset, etc).

A project known as STLPort, based on the SGI STL, maintains an up-to-date implementation of the STL, IOStreams and strings. Other projects also make variant custom implementations of the standard library with various design goals. Every C++ compiler vendor or distributor includes some implementation of the library, as this is required by the standard.

[Top]

Object-oriented features of C++

C++ introduces object-oriented features to C. It offers classes which provide the three essential object-oriented necessities: encapsulation, polymorphism, and inheritance.

[Top]

C++ encapsulation

C++ implements encapsulation by allowing all members of a class to be declared as either public, private, or protected. A public member of the class will be accessible to any function. A private member will only be accessible to functions that are members of that class and to functions and classes explicitly granted access permission by the class ("friends"). A protected member will be accessible to members of classes that inherit from the class in addition to the class itself and any friends.

It is possible to bypass encapsulation completely by declaring all members of the class public, but this defeats much of the purpose of object-oriented programming. It is generally considered good practice to make all data private, or at least protected, and to make public only those functions that are part of a minimal interface for users of the class that hides implementation details.

[Top]

Polymorphism

Polymorphism is the property of code that objects are treated differently based on their type. For example, a C++ program may contain this line of code:

sendPrintJob(device, printJob);

The print job could be an HTML document, the source code of a program, a photograph, or any number of other things. The device could be a printer, a fax machine, or something else. In each case, completely different code paths must execute based on the type of objects at hand. This is polymorphism at work.

In C, polymorphism of a sort can be achieved using the switch statement or function pointers. C++ provides two more sophisticated features for polymorphism: function overloading and virtual member functions. Both features allow a program to define several different implementations of a function for use with different types of objects.

Function overloading allows programs to declare multiple functions with the same name. The functions are distinguished by the number and types of their formal parameters. For example, a program might contain the following three function declarations:

void pageUser(int userid); void pageUser(int userid, string message); void pageUser(string username);

Three different pageUser() functions are declared. When the compiler afterwards encounters a call to pageUser(), it determines which function to call based on the number and type of the arguments provided. (The compiler considers only the parameters, not the return type.) Because the compiler determines which function to call at compile time, this is called static polymorphism. (The word static is used here in the sense of "not moving". It denotes that the determination is made based solely on static analysis of the source code: by reading it, not by running it. By the time the program executes, the decision has been made.)

Operator overloading is a form of function overloading. It is one of C++'s most controversial features. Many consider operator overloading to be widely misused, while others think it is a great tool for increasing expressiveness. An operator is one of the symbols defined in the C++ language, such as +, !=, <, or &. Much as function overloading allows the programmer to define different versions of a function for use with different argument types, operator overloading lets the programmer define different versions of an operator for use with different operand types. For example, if the class Integer contains a declaration like this:

Integer operator++();

then the program can use the ++ operator with objects of type Integer. For example, the code

Integer a = 2; ++a;

behaves exactly like this:

Integer a = 2; a.operator++();

In most cases, this would then increment the value of the variable a to 3. However, the programmer who created the Integer class can define the Integer::operator++() member function to do whatever he wants. Because operators are commonly used implicitly, it is considered bad style to declare an operator except when its meaning is obvious and unambiguous.

C++ templates make heavy use of static polymorphism, including overloaded operators.


Virtual member functions provide a different type of polymorphism. In this case, different objects that share a common base class may all support an operation in different ways. For example, a PrintJob base class might contain a member function

virtual int getPageCount(double pageWidth, double pageHeight)

Each different type of print job, such as DoubleSpacedPrintJob, may then override the method with a function that can calculate the appropriate number of pages for that type of job. In contrast with function overloading, the parameters for a given member function are always exactly the same number and type. Only the type of the object being called varies.

When a virtual member function of an object is called, the compiler sometimes doesn't know the type of the object at compile time and therefore can't determine which function to call. The decision is therefore put off until runtime. The compiler generates code to examine the object's type at runtime and determine which function to call. Because this determination is made on the fly, this is called dynamic polymorphism.

The run-time determination and execution of a function is called dynamic dispatch. In C++, this is commonly done using virtual tables.

[Top]

C++ inheritance

Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, inheritance is assumed to be private for a class base and public for a struct base. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.

Multiple inheritance is another controversial C++ feature. Multiple inheritance allows a class to derive from more than one base class; this can result in a complicated graph of inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as Java, accomplish something similar by allowing inheritance of multiple interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide no implementation).

[Top]

Design of C++

In The Design and Evolution of C++ ISBN 0-201-54330-3, Bjarne Stroustrup describes some rules that he uses for the design of C++. Knowing the rules helps to understand why C++ is the way it is. The following is a summary of the rules. Much more details can be found in The Design and Evolution of C++.

[Top]

History of C++

Stroustrup began work on C with Classes in 1979. The idea of creating a new language originated from Stroustrup's experience programming for his Ph.D. thesis. Stroustrup found that Simula had features that were very helpful for large software development but was too slow for practical uses, while BCPL was fast but too low level and unsuitable for large software development. When Stroustrup started working in Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his Ph.D. experience, Stroustrup set out to enhance the C language with Simula-like features. C was chosen because it is general-purpose, fast, and portable. At first, class (with data encapsulation), derived class, strong type checking, inlining, and default argument were features added to C.

As Stroustrup designed C with Classes (later C++), he also wrote Cfront, a compiler that generates C source codes from C with Classes source codes. The first commercial release occurred in October 1985.

In 1982, the name of the language was changed from C with Classes to C++. New features that were added to the language included virtual functions, function name and operator overloading, references, constants, user-controlled free-store memory control, improved type checking, and new comment style (//). In 1985, the first edition of The C++ Programming Language was released, providing an important reference to the language, as there was not yet an official standard. In 1989, Release 2.0 of C++ was released. New features included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990, The Annotated C++ Reference Manual was released and provided the basis for the future standard. Late addition of features included templates, exceptions, namespaces, new casts, and a Boolean type.

As the C++ language evolved, a standard library also evolved with it. The first addition to the C++ standard library was the stream I/O library which provided facilities to replace the traditional C functions such as printf and scanf. Later, among the most significant additions to the standard library, was the Standard Template Library.

After years of work, a joint ANSI-ISO committee standardized C++ in 1998 (ISO/IEC 14882:1998).

[Top]

Future development

C++ continues to evolve to meet future requirements. One group in particular works to make the most of C++ in its current form and advise the metaprogramming capabilities. The C++ standard does not cover implementation of name decoration, exception handling, and other implementation-specific features, making object code produced by different compilers incompatible; there are, however, 3rd-party standards for particular machines or OSs which attempt to standardise compilers on those platforms, for example .

C++ compilers still struggle to support the entire C++ standard, especially in the area of templates — a part of the language that was more-or-less entirely conceived by the standards committee. One particular point of contention is the export keyword, intended to allow template definitions to be separated from their declarations. The first compiler to implement export was Comeau C++, in early 2003 (5 years after the release of the standard); in 2004, Borland C++ Builder X was also released with export. Both of these compilers are based on the EDG C++ frontend. Other compilers such as Microsoft Visual C++ and GCC do not support it at all. partial template specialisation, which was poorly supported for several years after the C++ standard was released.

[Top]

History of the name "C++"

This name is credited to Rick Mascitti (mid-1983) and was first used in December 1983. Earlier, during the research period, the developing language had been referred to as "C with Classes". The final name stems from C's "++" operator (which increments the value of a variable) and a common naming convention of using "+" to indicate an enhanced computer program, for example: "BambooWeb+". According to Stroustrup: "the name signifies the evolutionary nature of the changes from C". C+ had earlier named an unrelated program.

Some C programmers have noted that if the statements x=3; and y=x++; are executed, then x==4 and y==3; x is incremented after its value is assigned to y. However, if the second statement is y=++x;, then y=4 and x=4. Following such reasoning, a more proper name for C++ might actually be ++C. However, c++ and ++c both increment c, and, on its own line, the form c++ is more common than ++c. A pedant may note that the introduction of C++ did not change the C language itself and the most accurate name might then be "C+1".

[Top]

C is not a subset of C++

While most C code consists of valid C++, C does not form a subset of C++. This is in contrast to Objective-C, another extension of C to support object-oriented programming.

For example, the following C program prints "C" when compiled with a C compiler, and it prints "C++" when compiled with a C++ compiler. This is due to C++'s stricter handling of types. In C the parameter to sizeof is automatically promoted to an int once evaluated, whereas C++ maintains the char type.

int main() { printf("%s\n", (sizeof('a') == sizeof(char)) ? "C++" : "C"); return 0; }

There are other differences as well. For example, C++ forbids calling the 'main' function from within the program, whereas this is legal in C.

[Top]

C++ examples

[Top]

Example 1

This is an example of a program which does nothing. It begins executing and immediately terminates. It consists of one thing: a main() function. main() is the designated start of a C++ program.

int main() { return 0; }

The C++ Standard requires that main() returns type int. A program which uses any other return type for main() is not Standard C++.

The Standard does not say what the return value of main() actually means. Traditionally, it is interpreted as the return value of the program itself. The Standard guarantees that returning zero from main() indicates successful termination.

Indicating unsuccessful termination from a C++ program is done by returning the EXIT_FAILURE constant, which is defined in the cstddef standard header.

[Top]

Example 2

This program also does nothing, but is less verbose.

int main() { }

In C++, falling off of the end of main() is equivalent to return 0;. This is not true for any function other than main().

[Top]

Example 3

This is an example of a Hello world program, which displays a message and then terminates.

#include <iostream> // needed for std::cout   int main() { std::cout << "Hello World!\n"; }
[Top]

Example 4

Modern C++ can accomplish advanced tasks in a simple manner. This example demonstrates the use of the C++ Standard Template Library containers map and C++ examples.

[Top]

See also

[Top]

References

[Top]




  View Live Article   This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License