Book creator (disable)

C++ Programming/Chapter Getting Started

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Contents

[edit]

Getting Started

[edit] Introducing C++

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

[edit] History

Bjarne Stroustrup a Computer Scientist, from Bell Labs was the designer and original implementer of 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, these and other features are covered in detail along this book.

The C++ programming language is a standard recognized by the ANSI (The American National Standards Institute), BSI (The British Standards Institute), DIN (The German national standards organization), several other national standards bodies, and was ratified in 1998 by the ISO (The International Standards Organization) as ISO/IEC 14882:1998, consists of two parts: the Core Language and the Standard Library; the latter includes the Standard Template Library and the Standard C Library (ANSI C 89).

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, run-time type identification, and more type checking in several cases. Comments starting with two slashes ("//") were originally part of BCPL, and was 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).

The current version, which is the 2003 version, ISO/IEC 14882:2003 redefines the standard language as a single item. The STL that pre-dated the standardization of C++, and was originally implemented in Ada is now an integral part of the standard and requirement for a compliant implementation of the same. Many other 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.

Since 2004, the standards committee (includes Bjarne Stroustrup) has been busy working out the details of a new revision of the standard, that has been temporarily titled C++0x, due publication in the end of 2011. Some implementations already support some of the proposed alterations.

C++ source code example
// 'Hello World!' program 
 
#include <iostream>
 
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}

Traditionally the first program people write in a new language is called "Hello World." because all it does is print the words Hello World. Hello World Explained offers a detailed explanation of this code; the included source code is to give you an idea of a simple C++ program.

[edit] Overview

Before you begin your journey to understand how to write programs using C++, it is important to understand a few key concepts that you may encounter. These concepts are not unique to C++, but are helpful to understanding computer programming in general. Readers who have experience in another programming language may wish to skim through or skip this section entirely.

There are many different kinds of programs in use today. From the operating system you use that makes sure everything works as it should, to the video games and music applications you use for fun, programs can fulfill many different purposes. What all programs (also called software or applications) have in common is that they all are made up of a sequence of instructions written in some form of programming language. These instructions tell a computer what to do, and generally how to do it. Programs can contain anything from instructions to solve math problems or send emails, to how to behave when a video game character is shot in a game. The computer will follow the instructions of a program one instruction at a time from start to finish.

[edit] Why learn C++?

Why not? This is the most clarifying approach to the decision to learn anything. Although learning is always good, selecting what you learn is more important as it is how you will prioritize tasks. Another side of this problem is that you will be investing some time in getting a new skill set. You must decide how will this benefit you. Check your objectives and compare similar projects or see what the programming market is in need of. In any case, the more programming languages you know, the better.

If you are approaching the learning process only to add another notch under your belt, that is, willing only to dedicate enough effort to understand its major quirks and learn something about its dark corners then you should be best served in learning first two other languages, this will clarify what makes C++ special in its approach to programming problems. You should select one imperative language, and in this C will probably have a better market value and will have a direct relation to C++ (a good substitute would be ASM) and the second language should be an Object Oriented language like Java for the same reasons, as there is a close relation between the three languages.

If you are willing to dedicate a more than passing interest in C++ then you can even learn C++ as your first language, but dedicate some time understanding the different paradigms and why C++ is a multi-paradigm language, or how some like to call it, a hybrid language.

Learning C is not a requirement for understanding C++, but knowing how to use an imperative language is, C++ will not make it easy for you to understand and distinguish some of this deeper concepts, since that in C++ you are free to implement solutions with a greater range of freedom. Understanding what options to make will become the cornerstone of mastering the language.

You should not learn C++ if you are only interested in applying or learning about Object Oriented Programing since the nomenclature used and some of the approaches C++ takes to the problem will probably increase the difficulty level in learning and mastering those concepts, if you are truly interested in Object Oriented programming, the best language for that is Smalltalk.

As with all languages C++ has a specific scope of application, where it can truly shine, and if we take a quick comparison with the previous mentioned languages, C++ is harder to learn than C and Java but more powerful than both. C++ enables you to abstract from the little things you have to deal with in C or other lower level languages but will grant you a bigger control and responsibility than Java, but it will not provide the default features you can obtain in similar higher level languages. You will have to search and examine several external implementations of these features and freely select those that best serve your purposes or you may even have to implement your own solution.

[edit] Where to get a compiler

When you select your compiler you must take in consideration your system OS, your personal preferences and the documentation that you can get on using it.

One of most actualized and compatible compilers is GCC. The next section will show how to get a copy and install it on Windows. You can easily find information on the GCC website on how to do it under another OS. GCC is a decent choice, and can be obtained for free. Many Open Source platforms include a recent GCC version. Version 4.0 or later gives fairly good conformance to the C++ standard. Various IDEs are available to support GCC. For Windows, Microsoft Visual Studio Express is currently available free of charge (but not free as in non-proprietary) with a C++ compiler that can be used from the command line or from the supplied IDE. An IDE, or Integrated Development Environment, is generally a graphical environment which integrates functionality like editing, compiling, linking, and usually a help system etc.).

NOTE:
In Appendix B:External References you will find references to other freely available compilers and even full IDEs you can use.

[edit] GCC

The GNU Compiler Collection is a free set of compilers developed by the Free Software Foundation, with Richard Stallman as one of the main architects.

There are many different pre-compiled GCC binaries on the Internet, some popular choices are listed below (with detailed steps for installation).

[edit] On Windows

Cygwin:

  1. Go to http://www.cygwin.com and click on the "Install Cygwin Now" button in the upper right corner of the page.
  2. Click "run" in the window that pops up, and click "next" several times, accepting all the default settings.
  3. Choose any of the Download sites ("ftp.easynet.be", etc.) when that window comes up; press "next" and the Cygwin installer should start downloading.
  4. When the "Select Packages" window appears, scroll down to the heading "Devel" and click on the "+" by it. In the list of packages that now displays, scroll down and find the "gcc-c++" package; this is the compiler. Click once on the word "Skip", and it should change to some number like "3.4" etc. (the version number), and an "X" will appear next to "gcc-core" and several other required packages that will now be downloaded.
  5. Click "next" and the compiler as well as the Cygwin tools should start downloading; this could take a while. While you're waiting, go to http://www.crimsoneditor.com and download that free programmer's editor; it's powerful yet easy to use for beginners.
  6. Once the Cygwin downloads are finished and you have clicked "next", etc. to finish the installation, double-click the Cygwin icon on your desktop to begin the Cygwin "command prompt". Your home directory will automatically be set up in the Cygwin folder, which now should be at "C:\cygwin" (the Cygwin folder is in some ways like a small Unix/Linux computer on your Windows machine -- not technically of course, but it may be helpful to think of it that way).
  7. Type "g++" at the Cygwin prompt and press "enter"; if "g++: no input files" or something like it appears you have succeeded and now have the gcc C++ compiler on your computer (and congratulations -- you have also just received your first error message!).

MinGW + DevCpp-IDE

  1. Go to http://www.bloodshed.net/devcpp.html, choose the version you want (eventually scrolling down), click on the appropriate download link! For the most current version, you will be redirected to http://www.bloodshed.net/dev/devcpp.html
  2. Scroll down to read the license and then to the download links. Download a version with Mingw/GCC. It's much easier than to do this assembling yourself. With a very short delay (only some days) you will always get the most current version of mingw packaged with the devcpp IDE. It's absolutely the same as with manual download of the required modules.
  3. You get an executable that can be executed at user level under any WinNT version. If you want it to be setup for all users, however, you need admin rights. It will install devcpp and mingw in folders of your wish.
  4. Start the IDE and experience your first project!
    You will find something mostly similar to MSVC, including menu and button placement. Of course, many things are somewhat different if you were familiar with the former, but it's as simple as a handfull of clicks to let your first program run.
[edit] For DOS

DJGPP:

  • Go to Delorie Software and download the GNU C++ compiler and other necessary tools. The site provides a Zip Picker in order to help identify which files you need, which is available from the main page.
  • Use unzip32 or other extraction utility to place files into the directory of your choice (ie. C:\DJGPP).
  • Set the envionment variables to configure DJGPP for compilation, by either adding lines to autoexec.bat or a custom batch file:
    set PATH=C:\DJGPP\BIN;%PATH%
    set DJGPP=C:\DJGPP\DJGPP.ENV
  • If you are running MS-DOS or Windows 3.1, you need to add a few lines to config.sys if they are not already present:
    shell=c:\dos\command.com c:\dos /e:2048 /p
    files=40
    fcbs=40,0

Note: The GNU C++ compiler under DJGPP is named gpp.

[edit] For Linux
  • For Redhat, get a gcc-c++ RPM, e.g. using Rpmfind and then install (as root) using rpm -ivh gcc-c++-version-release.arch.rpm
  • For Fedora Core, install the GCC C++ compiler (as root) by using yum install gcc-c++
  • For Mandrake, install the GCC C++ compiler (as root) by using urpmi gcc-c++
  • For Debian, install the GCC C++ compiler (as root) by using apt-get install g++
  • For Ubuntu, install the GCC C++ compiler by using sudo apt-get install g++
  • If you cannot become root, get the tarball from ftp://ftp.gnu.org/ and follow the instructions in it to compile and install in your home directory.
[edit] For Mac OS X

Xcode has GCC C++ compiler bundled. It can be invoked from the Terminal in the same way as Linux, but can also be compiled in one of XCode's projects.

[edit] What is a Programming Language?

In the most basic terms, a "programming language" is a means of communication between a human being (programmer) and a computer. A programmer uses this means of communication in order to give the computer instructions. These instructions are called "programs".

Like the many languages we use to communicate with each other, there are many languages that a programmer can use to communicate with a computer. Each language has its own set of words and rules, called semantics. If you're going to write a program, you have to follow the semantics of the language you're writing in, or you won't be understood.

Programming languages can basically be divided in to two categories: Low-Level and High-level, next we will introduce you to these concepts and their relevance to C++.

[edit] Low-level Languages

There are two general types of low level "languages".

Machine code (also called binary) is the lowest form of a low-level language. Machine code consists of a string of 0s and 1s, which combine to form meaningful instructions that computers can take action on. If you look at a page of binary it becomes apparent why binary is never a practical choice for writing programs; what kind of person would actually be able to remember what a bunch of strings of 1 and 0 mean ?

Assembly language (also called ASM), is just above machine code on the scale from low level to high level. It is a human-readable translation of the machine language instructions the computer executes. For example, instead of referring to processor instructions by their binary representation (0s and 1s), the programmer refers to those instructions using a more memorable (mnemonic) form. These mnemonics are usually short collections of letters that symbolize the action of the respective instruction, such as "ADD" for addition, and "MOV" for moving values from one place to another.

NOTE:
Assembly language is processor specific. This means that a program written in assembly language will not work on computers with different processor architectures.

You do not have to understand assembly language to program in C++, but it does help to have an idea of what's going on "behind-the-scenes". Learning about assembly language will also allow you to have more control as a programmer and help you in debugging and understanding code.

[edit] High-level Languages

Higher level languages partially solve the problem of abstraction to the hardware (CPU, co-processors, number of registers etc...) by providing portability of code. High-level languages do more with less code, although there is sometimes a loss in performance and less freedom for the programmer. They also attempt to use English language words in a form which can be read and generally interpreted by the average person with little experience in them. A program written in one of these languages is sometimes referred to as "human-readable code". In general, more abstraction makes it easier for a language be learned. No programming language is written in what one might call "plain English" though, (although BASIC comes close.) Because of this, the text of a program is sometimes referred to as "code", or more specifically as "source code." This is discussed in more detail in the Code Section of the book.

Keep in mind that this classification scheme is evolving. C++ is still considered a high-level language, but with the appearance of newer languages (Java, C#, Ruby etc...), C++ is beginning to be grouped with lower level languages like C.

[edit] Translating Programming Languages

Since a computer is only capable of understanding machine code, human-readable code must be either interpreted or translated into machine code.

An interpreter is a program (often written in a lower level language) that interprets the instructions of a program one instruction at a time into commands that are to be carried out by the interpreter as it happens. Typically each instruction consists of one line of text or provides some other clear means of telling each instruction apart and the program must be reinterpreted again each time the program is run.

A compiler is a program that translates the instruction of a program one instruction at a time into machine code. The translation into machine code may involve splitting one instruction understood by the compiler into multiple machine instructions. The instructions are only translated once and after that the machine can understand and follow the instructions directly whenever it is instructed to do so. A complete examination is given on the Compiler Section of the book.

The words and statements used to instruct the computer may differ, but no matter what words and statements are used, just about every programming language will include statements that will accomplish the following:

Input
Input is the act of getting information from a device such as a keyboard or mouse, or sometimes another program.
Output
Output is the opposite of input; it gives information to the computer monitor or another device or program.
Math/Algorithm
All computer processors (the brain of the computer), have the ability to perform basic mathematical computation, and every programming language has some way of telling it to do so.
Testing
Testing involves telling the computer to check for a certain condition and to do something when that condition is true or false. Conditionals are one of the most important concepts in programming, and all languages have some method of testing conditions.
Repetition
Perform some action repeatedly, usually with some variation.

An further examination is provided on the Statements Section of the book.

Believe it or not, that's pretty much all there is to it. Every program you've ever used, no matter how complicated, is made up of functions that look more or less like these. Thus, one way to describe programming is the process of breaking a large, complex task up into smaller and smaller subtasks until eventually the subtasks are simple enough to be performed with one of these simple functions.

C++ is mostly compiled rather than interpreted (there are some C++ interpreters), and then "executed" later. As complicated as this may seem, later you will see how easy it really is.

So as we have seen in the Introducing C++ Section, C++ evolved from C by adding some levels of abstraction (so we can correctly state that C++ is of a higher level than C). We will learn the particulars of those differences in the Programming Paradigms Section of the book and for some of you that already know some other languages should look into Programming Languages Comparisons Section.

[edit] Programming Paradigms

A programming paradigm is a style or model of programming that affects the way programmers can design, organize and write programs. A multi-paradigm programming language allows programmers to choose from a number of different programming paradigms. C++ is a multi-paradigm programming language.

[edit] Procedural Programming

Procedural programming can be defined as a subtype of imperative programming as a programming paradigm based upon the concept of procedure calls, in which statements are structured into procedures (also known as subroutines or functions). Procedure calls are modular and are bound by scope. A procedural program is composed of one or more modules. Each module is composed of one or more subprograms. Modules may consist of procedures, functions, subroutines or methods, depending on the programming language. Procedural programs may possibly have multiple levels or scopes, with subprograms defined inside other subprograms. Each scope can contain names which cannot be seen in outer scopes.

Procedural programming offers many benefits over simple sequential programming since procedural code:

  • is easier to read and more maintainable
  • is more flexible
  • facilitates the practice of good program design
  • allows modules to be reused in the form of code libraries.

[edit] Object-Oriented Programming

Object-oriented programming can be seen as an extension of procedural programming in which programs are made up of collection of individual units called objects that have a distinct purpose and function with limited or no dependencies on implementation. For example, a car is like an object; it gets you from point A to point B with no need to know what type of engine the car uses or how the engine works. Object-oriented languages usually provide a means of documenting what an object can and cannot do, like instructions for driving a car.

[edit] Objects and Classes

An object is composed of members and methods. The members (also called data members, characteristics, attributes, or properties) describe the object. The methods generally describe the actions associated with a particular object. Think of an object as a noun, its members as adjectives describing that noun, and its methods as the verbs that can be performed by or on that noun.

For example, a sports car is an object. Some of its members might be its height, weight, acceleration, and speed. An object's members just hold data about that object. Some of the methods of the sports car could be "drive", "park", "race", etc. The methods really don't mean much unless associated with the sports car, and the same goes for the members.

The blueprint that lets us build our sports car object is called a class. A class doesn't tell us how fast our sports car goes, or what color it is, but it does tell us that our sports car will have a member representing speed and color, and that they will be say, a number and a word, respectively. The class also lays out the methods for us, telling the car how to park and drive, but these methods can't take any action with just the blueprint - they need an object to have an effect.

[edit] Encapsulation

Encapsulation, the principle of information hiding (from the user), is the process of hiding the data structures of the class and allowing changes in the data through a public interface where the incoming values are checked for validity, and so not only it permits the hiding of data in an object but also of behavior. This prevents clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. In modern programming languages, the principle of information hiding manifests itself in a number of ways, including encapsulation and polymorphism.

[edit] Inheritance

This concept describes a relationship between two (or more) types, or classes, of objects in which one is said to be a "subtype" or "child" of the other, as result the "child" object is said to inherit features of the parent, allowing for shared functionality, this lets programmers re-use or reduce code and simplifies the development and maintenance of software.

Inheritance is also commonly held to include subtyping, whereby one type of object is defined to be a more specialized version of another type (see Liskov substitution principle), though non sub-typing inheritance is also possible.

Inheritance is typically expressed by describing classes of objects arranged in an inheritance hierarchy reflecting common behavior.

For example, one might create a variable class "Mammal" with features such as eating, reproducing, etc.; then define a subtype "Cat" that inherits those features without having to explicitly program them, while adding new features like "chasing mice". This allows commonalities among different kinds of objects to be expressed once and reused multiple times.

In C++ we can then have classes which are related to other classes (a class can be defined by means of an older, pre-existing, class ). This leads to a situation in which a new class has all the functionality of the older class, and additionally introduces its own specific functionality. Instead of composition, where a given class contains another class, we mean here derivation, where a given class is another class.

This OOP property will be explained further when we talk about Classes (and Structures) inheritance in the Classes Inheritance Section of the book.

If one wants to use more than one totally orthogonal hierarchy simultaneously, such as allowing "Cat" to inherit from "Cartoon character" and "Pet" as well as "Mammal" we are using multiple inheritance.

[edit] Multiple Inheritance

Multiple inheritance is the process by which one class can inherit the properties of two or more classes (variously known as its base classes, or parent classes, or ancestor classes, or super classes).

In some similar language, multiple inheritance is restricted in various ways to keep the language simple, such as by allowing inheritance from only one real class and a number of "interfaces", or by completely disallowing multiple inheritance. C++ places the full power of multiple inheritance in the hands of programmers, but it is needed only rarely, and (as with most techniques) can complicate code if used inappropriately. Because of C++'s approach to multiple inheritance, C++ has no need of separate language facilities for "interfaces"; C++'s classes can do everything that interfaces do in some related languages.

[edit] Polymorphism

Polymorphism allows a single name to be reused for several related but different purposes. The purpose of polymorphism is to allow one name to be used for a general class. Depending on the type of data, a specific instance of the general case is executed.

The concept of polymorphism is wider. Polymorphism exists every time we use two functions that have the same name, but differ in the implementation. They may also differ in their interface, e.g., by taking different arguments. In that case the choice of which function to make is via overload resolution, and is performed at compile time, so we refer to static polymorphism.

Dynamic polymorphism will be covered deeply in the Classes Section where we will address its use on redefining the method in the derived class.

[edit] Generic Programming

Generic programming or polymorphism is a programming style that emphasizes techniques that allow one value to take on different types as long as certain contracts such as subtypes and signature are kept. In simpler terms generic programming is based in finding the most abstract representations of efficient algorithms. Templates popularized the notion of generics. Templates allow code to be written without consideration of the type with which it will eventually be used. Templates are defined in the Standard Template Library (STL), where generic programming was introduced into C++.

[edit] Statically Typed

Typing refers to how a computer language handles its variables. Variables are values that the program uses during execution. These values can change; they are variable, hence their name. Static typing usually results in compiled code that executes more quickly. When the compiler knows the exact types that are in use, it can produce machine code that does the right thing easier. In C++, variables need to be defined before they are used so that compilers know what type they are, and hence is statically typed. Languages that are not statically typed are called dynamically typed.

Static typing usually finds type errors more reliably at compile time, increasing the reliability of compiled programs. Simply put, it means that "A round peg won't fit in a square hole", so the compiler will report it when a type leads to ambiguity or incompatible usage. However, programmers disagree over how common type errors are and what proportion of bugs that are written would be caught by static typing. Static typing advocates believe programs are more reliable when they have been type checked, while dynamic typing advocates point to distributed code that has proved reliable and to small bug databases. The value of static typing, then, presumably increases as the strength of the type system is increased.

A statically typed system constrains the use of powerful language constructs more than it constrains less powerful ones. This makes powerful constructs harder to use, and thus places the burden of choosing the "right tool for the problem" on the shoulders of the programmer, who might otherwise be inclined to use the most powerful tool available. Choosing overly powerful tools may cause additional performance, reliability or correctness problems, because there are theoretical limits on the properties that can be expected from powerful language constructs. For example, indiscriminate use of recursion or global variables may cause well-documented adverse effects.

Static typing allows construction of libraries which are less likely to be accidentally misused by their users. This can be used as an additional mechanism for communicating the intentions of the library developer.

[edit] Free-form

Free-form refers to how the programmer crafts the code. Basically, there are no rules on how you choose to write your program, save for the semantic rules of C++. Any C++ program should compile as long as it is legal C++.

The free-form nature of C++ is used (or abused, depending on your point of view) by some programmers in crafting obfuscated C++ (C++ that is purposefully written to be difficult to understand). The use of obfuscation is regarded by some as a security device, ensuring that the source code can is harder to analyzed by the average user.

[edit] Language Comparisons

There isn't a perfect language. It all depends on the tools and the objective. The optimal language (in terms of run-time performance) is machine code but machine code (binary) is the least efficient programming language in terms of coder time. The complexity of writing large systems is enormous with high-level languages, and beyond human capabilities with machine code. In the next section C++ will be compared with other closely related languages like C, Java, C# and C++/CLI.

The quote above is shown to indicate that no programming language at present can translate directly concepts or ideas into useful code, there are solutions that will help. We will cover the use of Computer-aided software engineering (CASE) tools that will address part of this problem but its use does require planning and some degree of complexity.

The intention of these sections is not to promote one language above another; each has its applicability. Some are better in specific tasks, some are simpler to learn, others only provide a better level of control to the programmer. This all may depend also on the level of control the programmer has of a given language.

[edit] Garbage Collection

In C++ garbage collection is optional rather than required. In the Garbage Collection Section of this book we will cover this issue deeply.

[edit] Why doesn't C++ include a finally keyword?

As we will see in the Resource Acquisition Is Initialization (RAII) Section of the book, RAII can be used to provide a better solution for most issues. When finally is used to clean up, it has to be written by the clients of a class each time that class is used (for example, clients of a File class have to do I/O in a try/catch/finally block so that they can guarantee that the File is closed). With RAII, the destructor of the File class can make that guarantee. Now the cleanup code has to be coded only once — in the destructor of File; the users of the class don't need to do anything.

TODO

TODO
Split this explanation to RAII and only provide the reference

[edit] Mixing Languages

TODO

TODO
Add relevant information

By default, C++ compilers normally "mangle" the names of functions in order to facilitate function overloading, and generic functions. In some cases, you need to gain access to a function that wasn't created in a C++ compiler. For this to occur, you need to declare a function as external:

extern "C" void LibraryFunction();

[edit] C 89/99

C was essentially the core language of C++ when Bjarne Stroustrup, decided to create a "better C". Many of the syntax conventions and rules still hold true and so we can even state that C was a subset of C++, most recent C++ compilers will also compile C code taking into consideration the small incompatibilities, since C99 and C++ 2003 are not compatible any more. You can also check more information about the C language on the C Programming Wikibooks ( http://en.wikibooks.org/wiki/C ).

C++ as defined by the ANSI standard in 98 (called C++98 at times) is very nearly, but not quite, a superset of the C language as it was defined by its first ANSI standard in 1989 (known as C89). There are a number of ways in which C++ is not a strict superset, in the sense that not all valid C89 programs are valid C++ programs, but the process of converting C code to valid C++ code is fairly trivial (avoiding reserved words, getting around the stricter C++ type checking with casts, declaring every called function, and so on).

In 1999, C was revised and many new features were added to it. As of 2004, most of these new "C99" features are not there in C++. Some (including Stroustrup himself) have argued that the changes brought about in C99 have a philosophy distinct from what C++98 adds to C89, and hence these C99 changes are directed towards increasing incompatibility between C and C++.

The merging of the languages seems a dead issue as coordinated actions by the C and C++ standards committees leading to a practical result didn't happen and it can be said that the languages started even to diverge.

Some of the differences are:

  • C++ supports function overloading (absent in C89, allowed only for some standard library code in C99).
  • C++ supports inheritance and polymorphism.
  • C++ adds keyword class, but keeps struct from C, with compatible semantics.
  • C++ supports access control for class members.
  • C++ supports generic programming through the use of templates.
  • C++ extends the C89 standard library with its own standard library.
  • C++ and C99 offer different complex number facilities.
  • C++ has bool and wchar_t as primitive types, while typedefs in C.
  • C++ comparison operators return bool, while C returns int.
  • C++ supports overloading of operators.
  • C++ character constants have type char, while C character constants have type int.
  • C++ has additional cast operators (static_cast, dynamic_cast, const_cast and reinterpret_cast).
  • C++ adds mutable keyword to address the imperfect match between physical and logical constness.
  • C++ extends the type system with references.
  • C++ supports member functions, constructors and destructors for user-defined types to establish invariants and to manage resources.
  • C++ supports runtime type identification (RTTI), via typeid and dynamic_cast.
  • C++ includes exception handling.
  • C++ has std::vector as part of its standard library instead of variable-length arrays as in C.
  • C++ treats sizeof operator as compile time operation, while C allows it be a runtime operation.
  • C++ has new and delete operators, while C uses malloc and free library functions exclusively.
  • C++ supports object-oriented programming without extensions.
  • C++ does not require use of macros and careful information-hiding and abstraction for code portability.
  • C++ supports per-line comments denoted by //. (C99 started official support for this comment system, and most compilers supported this as an extension.)
[edit] Reasons to chose one of the languages over the other

It is not uncommon to find someone defending C over C++ or vice versa or complain about some of those languages features. There is no scientific evidence to put most languages above another in general terms, the only reasons that do have some traction is if the language is still very recent and prone to deep changes or as yet unknown bugs, in the case of C or C++ this is not the case both languages are very mature even if both are still evolving, the new features keep an high level of compatibility with old code, making the use of those new constructs a programmer's decision. It is not uncommon to establish rules in a project to limit the use of parts of a language (such as RTTI, exceptions, or virtual-functions in inner loops), due the proficiency of the programmers or the needs of the project, as it is also common for new hardware to support lower level languages first. Due to C being less extensive and lower level than C++, it is easier to check and comply with strict industry guidelines and automate those steps. Another benefit is that it is easier for the programmer to do low level optimizations, even if most C++ compilers can guarantee near perfect optimizations automatically, a human can still do more and C has less complex structures.

Any of the valid reasons to choose a language over another is mostly due to programmers choice that indirectly deals with choosing the best tool for the job and having the resources needed to complete it. It would be hard to validate selecting C++ for a project if the available programmers only knew C or even the reverse, it is somewhat expected for a C++ programmer to produce functional C code, but the mindset and experience needed aren't the same, the same rational is valid for C programmers and ASM, this is due to the close relations that exist in the language structure and historic evolution.

One could argue that using the C subset of C++, in a C++ compiler, is the same as using C but in reality we find that it will generate slightly different results depending on the compiler used.

[edit] Java

This is a comparison of the Java programming language with the C++ programming language. C++ and Java share many common traits. You can get a better understanding of Java in the Java Programming WikiBook.

Java was created initially to support network computing on embedded systems. Java was designed to be extremely portable, secure, multi-threaded and distributed, none of which were design goals for C++. The syntax of Java was chosen to be familiar to C programmers, but direct compatibility with C was not maintained. Java also was specifically designed to be simpler than C++ but it keeps evolving above that simplification.

C++ Java
backwards compatible with C backwards compatibility with previous versions
execution efficiency developer productivity
trusts the programmer restrains the programmer's abilities
arbitrary memory access possible memory access only through objects
concise expression explicit operation
can arbitrarily override types type safety
procedural or object-oriented object-oriented
operator overloading meaning of operators immutable
powerful capabilities of language feature-rich, easy to use standard library

Differences between C++ and Java are:

  • C++ parsing is somewhat more complicated than with Java; for example, Foo<1>(3); is a sequence of comparisons if Foo is a variable, but it creates an object if Foo is the name of a class template.
  • C++ allows namespace level constants, variables, and functions. All such Java declarations must be inside a class or interface.
  • const in C++ indicates data to be 'read-only,' and is applied to types. final in java indicates that the variable is not to be reassigned. For basic types such as const int vs final int these are identical, but for complex classes, they are different.
  • C++ doesn't support constructor delegation.
  • C++ runs on the hardware, Java runs on a virtual machine so with C++ you have greater power at the cost of portability.
  • C++, int main() is a function by itself, without a class.
  • C++ access specification (public, private) is done with labels and in groups.
  • C++ access to class members default to private, in Java it is package access.
  • C++ classes declarations end in a semicolon.
  • C++ lacks language level support for garbage collection while Java has built-in garbage collection to handle memory deallocation.
  • C++ supports goto statements; Java does not, but its labeled break and labeled continue statements provide some structured goto-like functionality. In fact, Java enforces structured control flow, with the goal of code being easier to understand.
  • C++ provides some low-level features which Java lacks. In C++, pointers can be used to manipulate specific memory locations, a task necessary for writing low-level operating system components. Similarly, many C++ compilers support inline assembler. In Java, assembly code can still be accessed as libraries, through the Java Native Interface. However, there is significant overhead for each call.
  • C++ allows a range of implicit conversions between native types, and also allows the programmer to define implicit conversions involving compound types. However, Java only permits widening conversions between native types to be implicit; any other conversions require explicit cast syntax.
    • A consequence of this is that although loop conditions (if, while and the exit condition in for) in Java and C++ both expect a boolean expression, code such as if(a = 5) will cause a compile error in Java because there is no implicit narrowing conversion from int to boolean. This is handy if the code were a typo for if(a == 5), but the need for an explicit cast can add verbosity when statements such as if (x) are translated from Java to C++.
  • For passing parameters to functions, C++ supports both true pass-by-reference and pass-by-value. As in C, the programmer can simulate by-reference parameters with by-value parameters and indirection. In Java, all parameters are passed by value, but object (non-primitive) parameters are reference values, meaning indirection is built-in.
  • Generally, Java built-in types are of a specified size and range; whereas C++ types have a variety of possible sizes, ranges and representations, which may even change between different versions of the same compiler, or be configurable via compiler switches.
    • In particular, Java characters are 16-bit Unicode characters, and strings are composed of a sequence of such characters. C++ offers both narrow and wide characters, but the actual size of each is platform dependent, as is the character set used. Strings can be formed from either type.
  • The rounding and precision of floating point values and operations in C++ is platform dependent. Java provides a strict floating-point model that guarantees consistent results across platforms, though normally a more lenient mode of operation is used to allow optimal floating-point performance.
  • In C++, pointers can be manipulated directly as memory address values. Java does not have pointers—it only has object references and array references, neither of which allow direct access to memory addresses. In C++ one can construct pointers to pointers, while Java references only access objects.
  • In C++ pointers can point to functions or member functions (function pointers or functors). The equivalent mechanism in Java uses object or interface references.
  • C++ features programmer-defined operator overloading. The only overloaded operators in Java are the "+" and "+=" operators, which concatenate strings as well as performing addition.
  • Java features standard API support for reflection and dynamic loading of arbitrary new code.
  • Java has generics. C++ has templates.
  • Both Java and C++ distinguish between native types (these are also known as "fundamental" or "built-in" types) and user-defined types (these are also known as "compound" types). In Java, native types have value semantics only, and compound types have reference semantics only. In C++ all types have value semantics, but a reference can be created to any object, which will allow the object to be manipulated via reference semantics.
  • C++ supports multiple inheritance of arbitrary classes. Java supports multiple inheritance of types, but only single inheritance of implementation. In Java, a class can derive from only one class, but a class can implement multiple interfaces.
  • Java explicitly distinguishes between interfaces and classes. In C++ multiple inheritance and pure virtual functions makes it possible to define classes that function just as Java interfaces do.
  • Java has both language and standard library support for multi-threading. The synchronized keyword in Java provides simple and secure mutex locks to support multi-threaded applications. While mutex lock mechanisms are available through libraries in C++, the lack of language semantics makes writing thread safe code more difficult and error prone.
[edit] Memory management
  • Java requires automatic garbage collection. Memory management in C++ is usually done by hand, or through smart pointers. The C++ standard permits garbage collection, but does not require it; garbage collection is rarely used in practice. When permitted to relocate objects, modern garbage collectors can improve overall application space and time efficiency over using explicit deallocation.
  • C++ can allocate arbitrary blocks of memory. Java only allocates memory through object instantiation. (Note that in Java, the programmer can simulate allocation of arbitrary memory blocks by creating an array of bytes. Still, Java arrays are objects.)
  • Java and C++ use different idioms for resource management. Java relies mainly on garbage collection, while C++ relies mainly on the RAII (Resource Acquisition Is Initialization) idiom. This is reflected in several differences between the two languages:
    • In C++ it is common to allocate objects of compound types as local stack-bound variables which are destructed when they go out of scope. In Java compound types are always allocated on the heap and collected by the garbage collector (except in virtual machines that use escape analysis to convert heap allocations to stack allocations).
    • C++ has destructors, while Java has finalizers. Both are invoked prior to an object's deallocation, but they differ significantly. A C++ object's destructor must be implicitly (in the case of stack-bound variables) or explicitly invoked to deallocate the object. The destructor executes synchronously at the point in the program at which the object is deallocated. Synchronous, coordinated uninitialization and deallocation in C++ thus satisfy the RAII idiom. In Java, object deallocation is implicitly handled by the garbage collector. A Java object's finalizer is invoked asynchronously some time after it has been accessed for the last time and before it is actually deallocated, which may never happen. Very few objects require finalizers; a finalizer is only required by objects that must guarantee some clean up of the object state prior to deallocation—typically releasing resources external to the JVM. In Java safe synchronous deallocation of resources is performed using the try/finally construct.
    • In C++ it is possible to have a dangling pointer – a reference to an object that has been destructed; attempting to use a dangling pointer typically results in program failure. In Java, the garbage collector won't destruct a referenced object.
    • In C++ it is possible to have an object that is allocated, but unreachable. An unreachable object is one that has no reachable references to it. An unreachable object cannot be destructed (deallocated), and results in a memory leak. By contrast, in Java an object will not be deallocated by the garbage collector until it becomes unreachable (by the user program). (Note: weak references are supported, which work with the Java garbage collector to allow for different strengths of reachability.) Garbage collection in Java prevents many memory leaks, but leaks are still possible under some circumstances.
[edit] Libraries
  • C++ standard library only provides components that are relatively general purpose, such as strings, containers, and I/O streams. Java has a considerably larger standard library. This additional functionality is available for C++ by (often free) third party libraries, but third party libraries do not provide the same ubiquitous cross-platform functionality as standard libraries.
  • C++ is mostly backward compatible with C, and C libraries (such as the APIs of most operating systems) are directly accessible from C++. In Java, the richer functionality of the standard library is that it provides cross-platform access to many features typically available in platform-specific libraries. Direct access from Java to native operating system and hardware functions requires the use of the Java Native Interface.
[edit] Runtime
  • C++ is normally compiled directly to machine code which is then executed directly by the operating system. Java is normally compiled to byte-code which the Java virtual machine (JVM) then either interprets or JIT compiles to machine code and then executes.
  • Due to the lack of constraints in the use of some C++ language features (e.g. unchecked array access, raw pointers), programming errors can lead to low-level buffer overflows, page faults, and segmentation faults. The Standard Template Library, however, provides higher-level abstractions (like vector, list and map) to help avoid such errors. In Java, such errors either simply cannot occur or are detected by the JVM and reported to the application in the form of an exception.
  • In Java, bounds checking is implicitly performed for all array access operations. In C++, array access operations on native arrays are not bounds-checked, and bounds checking for random-access element access on standard library collections like std::vector and std::deque is optional.
[edit] Miscellaneous
  • Java and C++ use different techniques for splitting up code in multiple source files. Java uses a package system that dictates the file name and path for all program definitions. In Java, the compiler imports the executable class files. C++ uses a header file source code inclusion system for sharing declarations between source files. (See Comparison of imports and includes.)
  • Templates and macros in C++, including those in the standard library, can result in duplication of similar code after compilation. Second, dynamic linking with standard libraries eliminates binding the libraries at compile time.
  • C++ compilation features a textual preprocessing phase, while Java does not. Java supports many optimizations that mitigate the need for a preprocessor, but some users add a preprocessing phase to their build process for better support of conditional compilation.
  • In Java, arrays are container objects which you can inspect the length of at any time. In both languages, arrays have a fixed size. Further, C++ programmers often refer to an array only by a pointer to its first element, from which they cannot retrieve the array size. However, C++ and Java both provide container classes (std::vector and java.util.ArrayList respectively) which are resizable and store their size.
  • Java's division and modulus operators are well defined to truncate to zero. C++ does not specify whether or not these operators truncate to zero or "truncate to -infinity". -3/2 will always be -1 in Java, but a C++ compiler may return either -1 or -2, depending on the platform. C99 defines division in the same fashion as Java. Both languages guarantee that (a/b)*b + (a%b) == a for all a and b (b != 0). The C++ version will sometimes be faster, as it is allowed to pick whichever truncation mode is native to the processor.
  • The sizes of integer types is defined in Java (int is 32-bit, long is 64-bit), while in C++ the size of integers and pointers is compiler-dependent. Thus, carefully-written C++ code can take advantage of the 64-bit processor's capabilities while still functioning properly on 32-bit processors. However, C++ programs written without concern for a processor's word size may fail to function properly with some compilers. In contrast, Java's fixed integer sizes mean that programmers need not concern themselves with varying integer sizes, and programs will run exactly the same. This may incur a performance penalty since Java code cannot run using an arbitrary processor's word size.
[edit] Performance

Computing performance is a measure of resource consumption when a system of hardware and software performs a piece of computing work such as an algorithm or a transaction. Higher performance is defined to be 'using fewer resources'. Resources of interest include memory, bandwidth, persistent storage and CPU cycles. Because of the high availability of all but the latter on modern desktop and server systems, performance is colloquially taken to mean the least CPU cycles; which often converts directly into the least wall clock time. Comparing the performance of two software languages requires a fixed hardware platform and (often relative) measurements of two or more software subsystems. This section compares the relative computing performance of C++ and Java on common operating systems such as Windows and Linux.

Early versions of Java were significantly outperformed by statically compiled languages such as C++. This is because the program statements of these two closely related Level 6 languages may compile to a few machine instructions with C++, while compiling into several byte codes involving several machine instructions each when interpreted by a Java JVM. For example:

Java/C++ statement C++ generated code Java generated byte code
vector[i]++; mov edx,[ebp+4h]

mov eax,[ebp+1Ch]
inc dword ptr [edx+eax*4]

aload_1

iload_2
dup2
iaload
iconst_1
iadd
iastore

While this may still be the case for embedded systems because of the requirement for a small footprint, advances in just in time (JIT) compiler technology for long-running server and desktop Java processes has closed the performance gap and in some cases given the performance advantage to Java. In effect, Java byte code is compiled into machine instructions at run time, in a similar manner to C++ static compilation, resulting in similar instruction sequences.

C++ is still faster in most operations than Java at the moment, even at low-level and numeric computation. For in-depth information you could check Performance of Java versus C++. It's a bit pro-Java but very detailed.

[edit] C#

C# (pronounced "See Sharp") is a multi-purpose computer programming language suitable for all development needs. There is a WikiBook (http://en.wikibooks.org/wiki/C_sharp) that introduces C# language fundamentals and covers a variety of the base class libraries (BCL) provided by the Microsoft .NET Framework.

C# is very similar to Java in that it takes the basic operators and style of C++ but forces programs to be type safe, in that it executes the code in a controlled sandbox called the virtual machine. As such, all code must be encapsulated inside an object, among other things. C# provides many additions to facilitate interaction with Microsoft's Windows, COM, and Visual Basic.

There are several shortcomings to C++ which are resolved in C#. One of the more subtle ones is the use of reference variables as function arguments. When a code maintainer is looking at C++ source code, if a called function is declared in a header somewhere, the immediate code does not provide any indication that an argument to a function is passed as a reference. An argument passed by reference could be changed after calling the function whereas an argument passed by value cannot be changed. A maintainer not be familiar with the function looking for the location of an unexpected value change of a variable would additionally need to examine the header file for the function in order to determine whether or not that function could have changed the value of the variable. C# insists that the ref keyword be placed in the function call (in addition to the function declaration), thereby cluing the maintainer in that the value could be changed by the function.

TODO

TODO
Should refer MS & MONO and Portable.NET http://getdotgnu.com/pnet, as well as the ECMA and ISO standards for C# and CLI

[edit] Managed C++ (C++/CLI)

Managed C++ is a shorthand notation for Managed Extensions for C++, which are part of the .NET framework from Microsoft. This extension of the C++ language was developed to add functionality like automatic garbage collection and heap management, automatic initialization of arrays, and support for multidimensional arrays, simplifying all those details of programming in C++ that would otherwise have to be done by the programmer.

Managed C++ is not compiled to machine code. Rather, it is compiled to Common Intermediate Language, which is an object-oriented machine language and was formerly known as MSIL

[edit] D

The D programming language, also known simply as D, was developed in-house by Digital Mars, the language specification and D compiler (Windows and Linux) is freely distributed for free on their web site. Only the compiler front-end is licensed under both the Artistic License and the GNU GPL; sources for the front-end are distributed along with the compiler binaries. The compiler back-end is proprietary.

Digital Mars is a small US software company, also known for producing a C compiler (known over time as Datalight C compiler, then Zorland C and then Zortech C) and a C++ compiler (known as Zortech C++ that is attribute to be the first C++ compiler for Windows, renamed later as Symantec C++ and now Digital Mars C++ (DMC++) and associated to utilities such as an IDE for Windows (supporting the MFC library).

D originated as a re-engineering of C++, but even though it is predominantly influenced by that language, it is also a multi-paradigm language, it is not a variant of it. D has redesigned some C++ features and has been influenced by concepts used in other programming languages, such as Java, C# and Eiffel.

Wikibooks has a D Programming book, in this section we will point out some features were D is distinct from C++:

  • D does not support multiple inheritance.
TODO

TODO
Complete with distinctions from C++ to D

[edit] Chapter Summary

  1. Introducing C++ Development stage: 100% (as of Dec 11, 2006)
  2. Programming languages Development stage: 100% (as of Dec 11, 2006)
    1. Programming paradigms Development stage: 75% (as of Dec 11, 2006) - the versatility of C++ as a multi-paradigm language, concepts of Object-Oriented Programming (Objects and Classes, Inheritance, Polymorphism).
  3. Comparisons Development stage: 75% (as of Sep 20, 2005) - to other languages, relation to other computer science constructs and idioms.
    1. with C Development stage: 75% (as of Sep 20, 2005)
    2. with Java Development stage: 75% (as of Sep 20, 2005)
    3. with C# Development stage: 25% (as of Sep 20, 2005)
    4. with Managed C++ (C++/CLI) Development stage: 25% (as of Sep  20, 2005)
    5. with D Development stage: 25% (as of {{{2}}})