Loading
rss_feed

Bits & Bytes

Archive for the ‘C++’ Category

Keeping the C++ Console Window Open

One of the first problems that new C++ programmers have is keeping the console window open when writing C++ programs. The easiest solution to this problem is to use the Start Without Debugging option under the Debug the when executing programs. Unfortunately, Microsoft took this option and many others out of the default menus in Visual C++ 2010. To get this option back, select Tools->Settings->Expert Settings. Otherwise, you can use press (Ctrl + F5) to select Start Without Debugging without the menu.

That’s the simplest option for keeping the console window open. However, if you want to keep the window open when running an executable that you create, you will need to add some code to suspend execution and keep the window open. Below, we show one example of how to keep the window open by adding this line of code before the return statement:

system("pause");

The one objection I have to this method is that the system() function is not part of the C++ standard and may not be valid with some C++ compilers.

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    system("pause");
    return 0;
}

Alternatively, we could use cin.get(); to keep the window open like this:

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    cin.get();
    return 0;
}

However, using cin.get() can have problems if input is taken directly before it. The problem is that the input in the stream carries over to the cin.get() and causes the program to exit. To prevent this, we can add a call to clear() and ignore(), as we do below.

#include <iostream>

int main()
{
    using namespace std;

    int iInt;
    cin >> iInt;
    cout << "Input = " << iInt << endl;

    cin.clear();
    cin.ignore(0xFFFFFFFF, '\n');
    cin.get();
    return 0;
}

Operator Overloading in C++ – part 2

Continued . . .

Operator overloading offers advantages not only over C, but also over newer object-oriented languages as well. In these languages, we face the same problem. How do we make a sort that works on fundamental types and programmer-defined types? With an object-oriented structure, we can create an interface with a comparison function that all sortable types inherit. Then we can wrap native types, like double, with a class that inherits our interface, say Double. The technique of wrapping fundamental types in objects is often refered to as boxing. Converting from the wrapped type back to the fundamental type is called unboxing.

Boxing

double dTwo = 2.0;
Double qWrappedTwo = new Double(dTwo);

Unboxing

double dTwo = qWrappedTwo.GetValue();

With this technique, a single sort can work on all of our types. However, our data types suffer the memory inefficiency of the wrapping object and speed inefficiency of conversion from boxing and unboxing. Additionally, the conversions back and forth between fundamental and wrapped types is cumbersome. So, we see that templates and operator overloading offer advantages over other languages, particular in terms of speed and memory usage.

For programmers who work with numerical algorithms, operator overloading offers still more benefits. We can overload arithmetical operators to make object conform to the mathematical structures from abstract algebra like fields, rings, etc. For example, if we create a class for complex numbers or matrices, we might want to overload “+”, “*”, etc. It is important to use these operators properly. In this context, operator overloading can be very powerful.

One of the most common uses, and abuses, of operator overloading is the use of “+” to concatenate strings. Unfortunately, this usage is common in many languages and has even been used in the C++ STL string class. The STL has an elegant architecture to it, but this usage only seems to add confusion and further the idea of operator overloading as “syntactic sugar.” My problem with using “+” in string classes is that the usage does not conform to the intended mathematical meaning of the symbol.

Overloading a mathematical operator, like “+”, has many legitimate purposes in programming classes like quaternions, Taylor series, matrices, finite fields, complex numbers, vectors, polynomials, etc. If you are not working with mathematical types, overloading mathematical operators is probably a mistake.

Operator Overloading in C++ – part 1

Operator overloading in C++ is a topic that is full of confusion arising from two main sources: differences with other languages and chronic misuse. The rich and distinct structure of C++ provides the language with many features that have no counterpart in other languages. Hence, operator overloading is often seen from outside of C++ as unnecessary complexity; frequent misuse of this feature only serves to reinforce this perception. In reality, the peculiar strucure of C++ gives operator overloading a particularly powerful role in developing algorithms.

With all of the confusion surrounding operator overloading, it has frequently been refered as “syntactic sugar”–meaning that it serves to make code look nice. It may true that “a + b” is nicer looking than “sum(a, b)”, but the implications of the signature on the function that is being overloaded are far more significant.

Consider this simple bubblesort function:

template <typename PData>
void Bubblesort(PData xaArray[], int iLength) {
     for (int iEnd = iLength - 1; iEnd > 0; --iEnd) {
          for (int iIndex = 0; iIndex < iEnd; ++iIndex) {
               if (xaArray[iIndex] > xaArray[iIndex + 1]) {
                    PData xTemp  = xaArray[iIndex];
                    xaArray[iIndex]  = xaArray[iIndex + 1];
                    xaArray[iIndex + 1] = xTemp;
               }
           }
     }
}

Nevermind that this is a slow bubblesort, it could easily be any sorting algorithm. The important thing to note is that the algorithm works to sort any fundamental data type (int, double, etc.). It also works to sort any other data type that has overloaded the “>” and “=” operators.

That’s the power of operator overloading. It allows our algorithms to work on both fundamental and programmer-defined types. Better still, this algorithm uses the built-in operators for fundamental types so that no additional function call is needed for comparisons. Additionally, if we inline our overloaded operators on our programmer-defined types, we can avoid an expensive function call for comparisons on those types as well. Prior to C++ and operator overloading, C programmers used functions like qsort(), which is now in the file <cstdlib>, to sort arrays of any type of item. The declaration for qsort() looks like this:

void qsort( const void* kvpArray,
            size_t qNumberOfItems,
            size_t qItemSizeInBytes,
            int (*pfnCompareFn) ( const void *, const void *));

Notice that the last argument is a function pointer to a comparison function that is passed in. Since this is a function pointer, the comparison function cannot be inlined and that makes a quicksort in C much slower than a comparable version in C++ with operator overloading. Of course, you can get around this in C by writing a version of the sort for fundamental types and one for each new data type that you create. However, this was clearly seen as unmanageable, even by C programmers, or the qsort() function would not exist.

To be continued . . .