Programming Language Concepts Using C and C++/Introduction to Programming in C++

Plain C Program
Thanks to its unique relationship with C++, most C programs can be compiled as C++ programs with no or few modifications. This (that is, passing a C program as a C++ program) is not a recommended practice though; it’s advisable only when you have to use some preexisting C code in a C++ program.

C_Commands.cxx

In addition to the C-style comments C++ offers an alternative single-line comment that is delimited from the rest of the line with double slashes. Everything on the program line to the right of the delimiter is treated as a comment and ignored by the compiler.

C Commands in Namespace
C_Commands_In_NS.cxx

A C header file can be included from a C++ program in two different ways: using either its C or C++ name. Next line is an example to the latter. The C++ name of the C header file is prefixed with the letter c and the .h file suffix is dropped.

Since C++ library names are generally declared in a namespace, names included from header files are not visible unless we explicitly make them visible with a using directive. In the case of C library header files this is the std namespace. Failing to bring in the names found in this namespace means we must use all these names together with their namespaces. That is; omitting line 2 requires us to change line 4 to the following:



This may at times prove to be a useful tool. Consider calling a function4 that happens to have a name and signature clashing with one of those in the current namespace. Depending on whether you have imported this function via some using directive or not, simply issuing the name will lead to invocation of the function in the current namespace or a compile-time error. Fixing this error is possible by means of the scope operator and explicitly stating the namespace [and possibly class name] before the function name.



! style="text-align:left" | Example: Use of the scope operator.
 * }

Explicit referrals to names not living in a particular namespace&mdash;that is, names living in the global namespace&mdash;can be made through prefixing the scope operator to the function and/or class name. According to this, in case you may want to use the C-style-included  from within a C++ program, you must write the following:



As a final note keep in mind that C++-style inclusion of C facilities does not enable object-oriented style programming. You still have to call the functions like in C; there is no way of sending messages to objects.

C++ Program
C++_Commands.cxx

Yet better is using C++ like genuine C++! Functionality similar to that found in C header file stdio.h is found in C++ header file iostream. Like other names declared in standard library header files, names in iostream are declared in the  namespace.

The C++ compiler internally transforms the following line to



where  is an   object representing standard output (like stdout in C) and   is an   manipulator, which inserts a newline to the output stream and then flushes the   buffer (like   in C). << is an operator that is used to write output to some  object. As can be seen from the transformed line, it associates left to right. Thus the next line writes a message to the standard output and then appends a newline character to the end.

Note that the  operator is called twice in a row: once to output   and once to append an end-of-line character. That is, the following line is equivalent to

which is transformed to

This also shows the reason why the  operator must return an   object.

Linking C and C++ Programs
Next program is a C program and it was meant to be so; it is not a C program that is compiled as a C++ program.

C_File.c

Although next two functions do basically the same thing, we can neither express them in one single function nor give both of them the same name. This is because C does not support templates or overloading.

C++_Linking_With_C.cxx

The following  specification declares   and   to be functions that will be linked using C linkage. That is, no name mangling, except probably prepending an underscore, will take place. Alternatively, we could have written it as follows:

There are two definitions for the function named : one that takes an   argument and another that takes a   argument. Remember that this is a C++ program and C++ (thanks to a process called name mangling) supports function name overloading. This becomes possible by encoding the argument types in the function name and passing this transformed name to the linker. This makes type-safe linkage a non-issue. For instance, name of the first function below would be transformed [by the compiler] to  while the second one to. That is, the linker sees two different function names.

Although [unlike Java] the return type is taken into consideration in differentiating between overloaded functions, one should be very careful in using this property. This is because value returned from a C++ function can be ignored; a function may have been called for its side-effect. The following code fragment should make this clear.

C++ enables the parameterization of types by means of templates. The programmer parameterizes all or a subset of the types in the interface (the parameter and return types) of a function whose body otherwise remains invariant.

Unlike overloading, template mechanism does not require multiple definitions of a function by the programmer; instances of a particular function are constructed by the compiler. This process is referred to as template instantiation. It occurs implicitly as a side effect of either invoking a function template or taking the address of a function template.

Unlike C, C++ lets you mix declarative statements with executable ones. This means you can now declare identifiers just before their first points of reference; you don't have to declare them upon entry to the related block.

Depending on the argument type the function to be called is resolved at the compile time. Do not forget: what we do here is to call one of the preexisting functions, which happen to have the same name.

Each of the following invocations causes a different instance to be constructed by the compiler; with no invocations, the compiler would have made no instantiations.

Running the Program
In other environments where there is a port of the GNU Compiler Collection, such as Linux and Cygwin, you may see a message telling the command is not recognized. In such a case, try something like  or.

Default Arguments
Default_Arg.cxx

Arguments passed to some functions may for most cases have certain expected values, whereas in peculiar cases they may assume different values. For such situations C++ offers the use of default arguments as an option. For instance, consider a function for printing an integer. Giving the user an option of what base to print it in seems reasonable, but in most programs integers will be printed as decimal integer values. A function to print an integer using this facility would have the following prototype:

It is possible to provide default arguments for trailing arguments only.

The effect of a default argument can alternatively be achieved by overloading. The  function above can be expressed with the following functions:

C++ References
Reference.cxx

The following using directive is different than those we have already seen. It is not used for bringing all the names found in the entire namespace but a particular class found in the namespace; it will bring in the iostream class found in the std namespace while all other classes/functions in the same namespace will be invisible and therefore can only be used with the help of the scope operator.

The following line is an example to the usage of references in C++. References are used to provide the call-by-reference semantics. They help programmers write code that is cleaner and much easier to understand than the code that would have been written using pointers. Call-by-reference semantics simulated by means of pointers and all its chores are done by the compiler [like var parameters in Pascal or ref parameters in C#].

Pragmatically, a reference may be seen as an alias for another variable. While passing an argument, formal parameter becomes an alias for the corresponding actual parameter. Technically, it is a constant pointer to another variable. For this reason a reference must be initialized at the point of its definition. That is,

Once defined to be so, a reference cannot be made to refer to another variable. That is, given the above definitions,

will not cause  to become an alias for. It will rather set  and, through ,   to.

Accordingly, transformed code corresponding to the following function will be as given below:

Its undeniable flexibility aside, special relationship of arrays and pointers in C/C++ may at times lead to difficult to find run-time errors. Take the following equivalent declarations, for instance.

Compiler will eventually convert the first two declarations to the third one, which means we can pass an array of any length. This is in stark contrast with the intentions of the first declaration. A consequence of this is the programmer, together with the user, should try harder to avoid any possible run-time errors such as using out-of-bounds index values.

Next line is a type definition that we will be utilizing in stricter type checking of array arguments. It defines a reference to an array of five s. Any array identifier claiming to be of this type will not only be checked for component type but also for its length. For instance, any attempts to pass an array of size other than five to  will be caught as a compile-time error.

It should be emphasized that this is valid for arrays whose sizes can be determined at compile-time. C++ compiler does not incorporate any run-time checks, which would slow down the program and therefore would not go well with the design philosophy of C/C++, into the resulting object code. For this reason, the following fragment will not even compile.

Now that a reference is a constant pointer, the following can be seen as follows:

That is, the following  defines a synonym, , for function reference type that takes an   and returns an. In other words, any function that takes an  and returns an , such as   or  , may be considered to be an instance of.

Next function shows an alternative way of implementing the callback mechanism in C++. The side-effect produced by  depends on the function passed to it as its argument.

No address-of operators! Everything is taken care of by the compiler. All user has to know is that the side effects that take place in the function are permanent.

Stream Manipulators
All stream objects in C++, such as cout and cin, maintain a state information that can be used to control the details of input/output operations. This includes attributes like precision of a floating-point number, width of tabulated data, and so on. What follows is a simple program to demonstrate some of the manipulators found in C++.

Manipulators.cxx

A manipulator modifies the internal state of a stream object and causes subsequent input/output to be performed differently; it does not write to or read from the underlying stream. in the following statement, for instance, reserves as many characters of space as the value passed in the argument for output of the next argument;  writes all subsequent output&mdash;until it's changed with another manipulator such as  &mdash;in a left-justified manner

In case output produced does not fill up all space reserved for it we choose to fill the empty spaces left with the underline character; whatever integral value is written to the window of twelve characters will be written in a right-justified manner using hexadecimal notation and this will be relayed to the user, thanks to the  manipulator, by prefixing the output.

Next line initializes the local variable precision with the default precision value. This happens to be 6, which means six digits are written after the decimal point. If you crave for higher precision you can pass it as an argument to the same function or use  in a similar fashion.

Running the Program
Output.dat