Search

The Online Encyclopedia and Dictionary

 
     
 

Encyclopedia

Dictionary

Quotes

   
 

C Plus Plus

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.

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.

In C and C++, the expression x++ increases the value of x by 1. The name "C++" is a play on this, suggesting an improvement upon C.

Contents

Technical overview

The 1998 C++ Standard consists of two parts: the Core Language and the Standard Library; the latter includes most of the Standard Template Library and a slightly modified version of the C 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.

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.

C++ library

The C++ standard library incorporates the C standard library with some small modifications to make it work better with the C++ language. Another large part of the C++ library is based on the Standard Template Library (STL). This provides such useful tools as containers (for example vectors and lists) and iterators (generalized pointers) to provide these containers with array-like access. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any container or on any sequence defined by 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, since this is an important part of the standard and is expected by users.

Object-oriented features of C++

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

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.

Encapsulation without polymorphism can also be used to provide abstract data types.

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. Curiously, it can be argued that the standard libraries do not follow this convention. For example, the object cout, used for outputting text to the console, has an overloaded << operator for outputting the text. Critics argue that this is use is non-obvious because << is the operator for a bit shift, which is clearly meaningless in this context. Nevertheless, most people consider this use to be acceptable, and this particular example is certainly in C++ to stay.

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 for which this method is 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.

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).

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++.

  • C++ is designed to be a statically typed, general-purpose language that is as efficient and portable as C
  • C++ is designed to directly and comprehensively support multiple programming styles (procedural programming, data abstraction, object-oriented programming, and generic programming)
  • C++ is designed to give the programmer choice, even if this makes possible for the programmer to choose incorrectly
  • C++ is designed to be as compatible with C as possible, therefore providing a smooth transition from C
  • C++ avoids features that are platform specific or not general purpose
  • C++ does not incur overhead for features that are not used
  • C++ is designed to function without a sophisticated programming environment

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 1983, 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). For some years after the official release of the standard in 1998, the committee processed defect reports, and published a corrected version of the C++ standard in 2003.

No one owns the C++ language; it is royalty-free. The standard document itself is, however, not available for free.

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 C++ standards committee which features work well and which need improving: Boost.org. Current work indicates that C++ will capitalize on its multi-paradigm nature more and more. The work at Boost.org, for example, is greatly expanding C++'s functional and 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 [1] http://www.codesourcery.com/cxx-abi/ .

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, beta compiler of 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. Herb Sutter , secretary of the C++ standards committee, has recommended that export be removed from future versions of the C++ standard [2] http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf , but finally the decision was made to leave it in the C++ standard.

Other template issues include constructions such as partial template specialisation, which was poorly supported for several years after the C++ standard was released.

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: "Wikipedia+". 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".

C++ is not a superset of C

While most C code is also valid C++, C++ does not form a superset of C: there exists valid C code that is not valid C++. This is in contrast to Objective-C, another extension of C to support object-oriented programming, which is a superset of C.

Furthermore, code that is both valid C and valid C++ may produce different results depending upon whether it is compiled as C or C++. For example, the following program prints "C" when compiled with a C compiler but prints "C++" when compiled with a C++ compiler. This is because in C the type of a character literal (such as 'a') is int, whereas in C++ it is char.

 #include <stdio.h>
 
 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. In addition, C++ is much stricter about various features; for example, it lacks implicit type conversion between unrelated pointer types and does not allow a function to be used that has not yet been declared.

See this section of the C article for more details.

C++ examples

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.

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().

Example 3

This is an example of a Hello world program, which uses the Standard Library (not STL) cout facility to display a message and then terminates.

 #include <iostream> // Required for std::cout and std::endl
  
 int main()
 {  
     std::cout << "Hello World!" << std::endl;
 }

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 vector , among other features.

 #include <iostream>   // std::cout
 #include <vector>     // std::vector<>
 #include <map>        // std::map<> and std::pair<>
 #include <algorithm>  // std::for_each()
 #include <string>     // std::string
  
 using namespace std;  // import "std" namespace into global namespace
  
 void display_item_count(pair< string const, vector<string> > const& person) {
    // person is a pair of two objects: person.first is person's name,
    // person.second is a list of person's items (vector of strings)
    cout << person.first << " is carrying " << person.second.size() << " items\n";
 }
  
 int main() {
    // Declare a map with string keys and vectors of strings as data
    map< string, vector<string> > items;
     
    // Add some people to the map and let them carry some items
    items["Anya"].push_back("scarf");
    items["Dimitri"].push_back("tickets");
    items["Anya"].push_back("puppy");
     
    // Iterate over all the items in the container
    for_each(items.begin(), items.end(), display_item_count);
 }

In this example, the using declaration was used for brevity though in a real-life program, its use should be much more restricted. Using directives, which are more specific than declarations, are usually recommended :

 #include <vector>
  
 int main()
 {
  using std::vector;
   
  vector<int> my_vector;
 }

Note that the directive was put at function scope, which reduces chances of clashing (which was the reason for which namespaces were introduced in the language). Using declarations, dumping whole namespaces in the global one, defeat the very essence of namespaces.

Check out more C++ examples.

See also

References

External links

  • Online C++ Tutorial http://www.intap.net/~drw/cpp/
  • Bjarne Stroustrup's homepage http://www.research.att.com/~bs/homepage.html
  • Programming:C plus plus Wikibook http://wikibooks.org/wiki/Programming:C_plus_plus
  • C++ FAQ Lite by Marshall Cline http://www.parashift.com/c%2B%2B-faq-lite/
  • GNAcademy.Org TWiki C++ Web http://www.gnacademy.org/twiki/bin/view/CPP/WebHome
  • Internet sites and files of interest to C++ users http://www.robertnz.net/cpp_site.html , A categorised list of C++ related links.
  • University of Cambridge Department of Engineering list of C++ links http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html
  • Boost.org: C++ high quality libraries http://www.boost.org/
  • CProgramming.com http://www.cprogramming.com/
  • C/C++ Users Journal http://www.cuj.com/
  • The C++ Annotations http://www.icce.rug.nl/documents/cplusplus/
  • C/C++ Reference http://cppreference.com/
  • How to Think Like a Computer Scientist http://ibiblio.org/obp/thinkCS/ C++ version
  • Free book "Thinking in C++" http://mindview.net/Books/TICPP/ThinkingInCPP2e.html by Bruce Eckel
  • C2.com Discussion http://www.c2.com/cgi/wiki?CeePlusPlus
  • Hyperlinked C++ BNF Grammar http://www.nongnu.org/hcb/
  • Common Text Transformation Library http://cttl.sourceforge.net/index.html
  • Parsing C++ http://www.nobugs.org/developer/parsingcpp/
  • Testing C++ Compilers for ISO Language Conformance http://www.cs.clemson.edu/~malloy/projects/ddj2/ddj2.html
  • Free book "C++: A Dialog" http://www.steveheller.com/cppad/Output/dialogTOC.html by Steve Heller
  • Embedded C++ Homepage http://www.caravan.net/ec2plus/
  • Standards Committee Page: JTC1/SC22/WG21 - C++ http://www.open-std.org/jtc1/sc22/wg21/
  • Association of C and C++ Users http://www.accu.org/ ACCU
  • Somewhat dated [draft of the C++ standard ftp://ftp.research.att.com/pub/c++std/WP/CD2/ ]


Major programming languages (more)

Ada | ALGOL | APL | AWK | BASIC | C | C++ | C# | COBOL | Delphi | Eiffel | Fortran | Haskell | IDL | Java | JavaScript | Lisp | LOGO | ML | Objective-C | Pascal | Perl | PHP | PL/I | Prolog | Python | Ruby | SAS | Scheme | sh | Simula | Smalltalk | SQL | Visual Basic




Last updated: 02-08-2005 13:00:32
Last updated: 05-03-2005 02:30:17