C Plus Plus

The title of this article is incorrect because of 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 C++ 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.

It is important to realize that, officially, there is no longer a single language called "C++"; the term denotes a family of related languages, each usually a slightly incompatible superset of a previously defined one. Early members of this family used to be identified by version number, later members are distinguished by the year in which that specific language has been standardized.

Features introduced in 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 variadic macros and better handling of arrays as parameters.

A very common source of confusion is a subtle terminology issue: because of its derivation from C, in C++ the term object means memory area, just like in C, and not class instance, which is what it means in most other object oriented languages. For example in both C and C++ the line

   int i;

defines an object of type int, that is the memory area where the value of the variable i will be stored on assignment.

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 some object-oriented features to C. It offers classes which provide the four features commonly present in OO (and some non OO) languages: abstraction, encapsulation, polymorphism, and inheritance.

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.

The OO principle is that all and only the functions that can access the internal representation of a type should be encapsulated within the type definition. C++ supports this (via member functions and friend functions), but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and is also allowed to make public entities that are not part of the representation of the type. Because of this C++ supports not just OO programming but other weaker decomposition paradigms, like modular 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.

Polymorphism

Polymorphism is a widely used and abused term that is not well defined.

In the case of C++ it is often used in connection with member function names, where the function name corresponds to several implementations, and which implementation gets invoked depends either on the type of the arguments (static polymorphism) or on the type of the class instance value (dynamic polymorphism) used on which the virtual member function is invoked.

For example, a C++ program may contain something like this:

   /* Static polymorphism */
   
   extern void SendJobToDevice(PrintJobText *,DeviceLaser *);
   extern void SendJobToDevice(PrintJobText *,DeviceJet *);
   extern void SendJobToDevice(PrintJobHTML *,DeviceLaser *);
   extern void SendJobToDevice(PrintJobHTML *,DeviceJet *);
   ...
   SendJobToDevice(printJob,device);
   /* Dynamic polymorphism */
   
   class Device {
   public:
     virtual void print(PrintJob*);
     ...
   };
   PrintJob *printJob;
   Device *device;
   ...
   device->print(printJob);
   // Note that since C++ does not have multiple dispatch, the above
   // function call is polymorphic only based on the device's type.

In C, (dynamic) 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 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.

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 it 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


Please refer to the indepth book on C++ Internals by Stanley B. Lippman (he worked on implementing/maintaining C-front the original C++ implementation at Bell Labs). "Inside the C++ Object Model" documents how the C++ compiler converts your program statements into an in-memory layout.

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. It should also be noted that many C++ books provide example code for implementing the keyword export (Ivor Horton's Beginning ANSI C++, pg. 827) which will not compile, but there is no reference to the problem with the keyword export mentioned. 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+ was the name of an earlier, unrelated programming language.

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. However, the introduction of C++ did not change the C language itself, so an even more accurate name might 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.

A common portability issue from C to C++ are the numerous additional keywords that C++ introduced. This makes C code that uses them as identifiers illegal in C++. For example:

struct template {
    int new;
    struct class *class;
};

is legal C code, but is rejected by a C++ compiler, since the keywords "template", "new" and "class" are not appropriate in the corresponding places.

See the relation to C++ 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 is an example of a Hello world program, which uses the C++ 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;
    return 0;
}

Example 3

#include <iostream>
#include <cstdlib>  /*calls the headers responsible for the interaction between the computer and the user.*/

int main()
{
 int response;

 cout << "Are you feeling well? (1=Yes, 2=No)";
 cin >> response;

 if (response == 1) {cout << "I am glad that you are fine.";}
 else               {cout << "Oh, I am so sorry.";}

 return 0;
}

This program asks for a user input (with cout), and stores the subsequent information in the 'response' variable. This is then used in the if( block to make a decision as to which message should be displayed.

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);
   return 0;
}

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

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

Note that the declaration was put at function scope, which reduces chances of clashing (which was the reason for which namespaces were introduced in the language). Dumping whole namespaces in the global namespace, with using directives, defeats the very purpose of namespaces.

Check out more C++ examples.

See also

References

External links

Template:Wikicities

Compilers

Template:Major programming languages smallar:سي بلس بلس bg:Си плюс плюс ca:C plus plus cs:Cplusplus da:C plus plus de:C-Plusplus et:C pluss pluss es:C ms ms eo:C Plus Plus fr:C plus plus ko:C 플러스 플러스 it:C plus plus he:C Plus Plus lt:C plius plius nl:Programmeertaal Cplusplus ja:C Plus Plus no:C Pluss Pluss pl:C plus plus pt:C mais mais ro:C plus plus ru:Си плюс плюс sk:C Plus Plus fi:C plus plus sv:C Plus Plus tr:C artı artı uk:C Plus Plus zh:C++

Navigation

  • Art and Cultures
    • Art (https://academickids.com/encyclopedia/index.php/Art)
    • Architecture (https://academickids.com/encyclopedia/index.php/Architecture)
    • Cultures (https://www.academickids.com/encyclopedia/index.php/Cultures)
    • Music (https://www.academickids.com/encyclopedia/index.php/Music)
    • Musical Instruments (http://academickids.com/encyclopedia/index.php/List_of_musical_instruments)
  • Biographies (http://www.academickids.com/encyclopedia/index.php/Biographies)
  • Clipart (http://www.academickids.com/encyclopedia/index.php/Clipart)
  • Geography (http://www.academickids.com/encyclopedia/index.php/Geography)
    • Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
    • Maps (http://www.academickids.com/encyclopedia/index.php/Maps)
    • Flags (http://www.academickids.com/encyclopedia/index.php/Flags)
    • Continents (http://www.academickids.com/encyclopedia/index.php/Continents)
  • History (http://www.academickids.com/encyclopedia/index.php/History)
    • Ancient Civilizations (http://www.academickids.com/encyclopedia/index.php/Ancient_Civilizations)
    • Industrial Revolution (http://www.academickids.com/encyclopedia/index.php/Industrial_Revolution)
    • Middle Ages (http://www.academickids.com/encyclopedia/index.php/Middle_Ages)
    • Prehistory (http://www.academickids.com/encyclopedia/index.php/Prehistory)
    • Renaissance (http://www.academickids.com/encyclopedia/index.php/Renaissance)
    • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
    • United States (http://www.academickids.com/encyclopedia/index.php/United_States)
    • Wars (http://www.academickids.com/encyclopedia/index.php/Wars)
    • World History (http://www.academickids.com/encyclopedia/index.php/History_of_the_world)
  • Human Body (http://www.academickids.com/encyclopedia/index.php/Human_Body)
  • Mathematics (http://www.academickids.com/encyclopedia/index.php/Mathematics)
  • Reference (http://www.academickids.com/encyclopedia/index.php/Reference)
  • Science (http://www.academickids.com/encyclopedia/index.php/Science)
    • Animals (http://www.academickids.com/encyclopedia/index.php/Animals)
    • Aviation (http://www.academickids.com/encyclopedia/index.php/Aviation)
    • Dinosaurs (http://www.academickids.com/encyclopedia/index.php/Dinosaurs)
    • Earth (http://www.academickids.com/encyclopedia/index.php/Earth)
    • Inventions (http://www.academickids.com/encyclopedia/index.php/Inventions)
    • Physical Science (http://www.academickids.com/encyclopedia/index.php/Physical_Science)
    • Plants (http://www.academickids.com/encyclopedia/index.php/Plants)
    • Scientists (http://www.academickids.com/encyclopedia/index.php/Scientists)
  • Social Studies (http://www.academickids.com/encyclopedia/index.php/Social_Studies)
    • Anthropology (http://www.academickids.com/encyclopedia/index.php/Anthropology)
    • Economics (http://www.academickids.com/encyclopedia/index.php/Economics)
    • Government (http://www.academickids.com/encyclopedia/index.php/Government)
    • Religion (http://www.academickids.com/encyclopedia/index.php/Religion)
    • Holidays (http://www.academickids.com/encyclopedia/index.php/Holidays)
  • Space and Astronomy
    • Solar System (http://www.academickids.com/encyclopedia/index.php/Solar_System)
    • Planets (http://www.academickids.com/encyclopedia/index.php/Planets)
  • Sports (http://www.academickids.com/encyclopedia/index.php/Sports)
  • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
  • Weather (http://www.academickids.com/encyclopedia/index.php/Weather)
  • US States (http://www.academickids.com/encyclopedia/index.php/US_States)

Information

  • Home Page (http://academickids.com/encyclopedia/index.php)
  • Contact Us (http://www.academickids.com/encyclopedia/index.php/Contactus)

  • Clip Art (http://classroomclipart.com)
Toolbox
Personal tools