In order to relieve programmers from dealing with computer-related terms, modern programming languages use abstractions so that a list of strings, for example, can be handled and thought of as a list of strings rather than a list of addresses that we may easily lose track of if we make the slightest typo. Not only do the abstractions relieve the programmers from bugs, they also make the code more expressive by using concepts from the domain of the application. In other words, the code is expressed in terms that are closer to a spoken language than if expressed with abstract programming keywords.
C++ and C are nowadays two completely different languages. Still, C++ is highly compatible with C and has inherited a lot of its syntax and idioms from C. To give you some examples of C++ abstractions we will here show how a problem can be solved in both C and C++.
Take a look at the following C/C++ code snippets, which correspond to the question: "How many copies of Hamlet is in the list of books?". We begin with the C version:
// C version
struct string_elem_t { const char* str_; string_elem_t* next_; };
int num_hamlet(string_elem_t* books) {
const char* hamlet = "Hamlet";
int n = 0;
string_elem_t* b;
for (b = books; b != 0; b = b->next_)
if (strcmp(b->str_, hamlet) == 0)
++n;
return n;
}
The equivalent version using C++ would look something like this:
// C++ version
int num_hamlet(const std::list<std::string>& books) {
return std::count(books.begin(), books.end(), "Hamlet");
}
Although the C++ version is still more of a robot language than a human language, a lot of programming lingo is gone. Here are some of the noticeable differences between the preceding two code snippets:
- The pointers to raw memory addresses are not visible at all
- The std::list<std::string> container is an abstraction of string_elem_t
- The std::count() method is an abstraction of both the for loop and the if condition
- The std::string class is (among other things) an abstraction of char* and strcmp
Basically, both versions of num_hamlet() translate to roughly the same machine code, but the language features of C++ makes it possible to let the libraries hide computer related terminology such as pointers. Many of the modern C++ language features can be seen as abstractions of basic C functionality and, on top of that, basic C++ functionality:
- C++ classes are abstractions of C-structs and regular functions
- C++ polymorphism is the abstraction of function pointers
On top of that, some recent C++ features are abstractions of former C++ features:
- C++ lambda functions are abstractions of C++ classes
- Templates are abstractions of generating C++ code