Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]
  • Table Of Contents Toc
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

By : Dorothy R. Kirk
5 (13)
close
close
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

5 (13)
By: Dorothy R. Kirk

Overview of this book

Even though object-oriented software design enables more easily maintainable code, companies choose C++ as an OO language for its speed. Object-oriented programming in C++ is not automatic – it is crucial to understand OO concepts and how they map to both C++ language features and OOP techniques. Distinguishing your code by utilizing well-tested, creative solutions, which can be found in popular design patterns, is crucial in today’s marketplace. This book will help you to harness OOP in C++ to write better code. Starting with the essential C++ features, which serve as building blocks for the key chapters, this book focuses on explaining fundamental object-oriented concepts and shows you how to implement them in C++. With the help of practical code examples and diagrams, you’ll learn how and why things work. The book’s coverage furthers your C++ repertoire by including templates, exceptions, operator overloading, STL, and OO component testing. You’ll discover popular design patterns with in-depth examples and understand how to use them as effective programming solutions to solve recurring OOP problems. By the end of this book, you’ll be able to employ essential and advanced OOP concepts to create enduring and robust software.
Table of Contents (30 chapters)
close
close
1
Part 1: C++ Building Block Essentials
6
Part 2: Implementing Object-Oriented Concepts in C++
13
Part 3: Expanding Your C++ Programming Repertoire
19
Part 4: Design Patterns and Idioms in C++
25
Part 5: Considerations for Safer Programming in C++

Reviewing basic C++ language syntax

In this section, we will briefly review basic C++ syntax. We’ll assume that you are either a C++ programmer with non-OO programming skills, or that you’ve programmed in C, Java, or a similar strongly typed checked language with related syntax. You may also be a long-standing professional programmer who is able to pick up another language’s basics quickly. Let’s begin our brief review.

Comment styles

Two styles of comments are available in C++:

  • The /*   */ style provides for comments spanning multiple lines of code. This style may not be nested with other comments of this same style.
  • The // style of comment provides for a simple comment to the end of the current line.

Using the two comment styles together can allow for nested comments, which can be useful when debugging code.

Variable declarations and standard data types

Variables may be of any length, and may consist of letters, digits, and underscores. Variables are case sensitive and must begin with a letter or an underscore. Standard data types in C++ include the following:

  • int: To store whole numbers
  • float: To store floating point values
  • double: To store double precision floating point values
  • char: To store a single character
  • bool: For boolean values of true or false

Here are a few straightforward examples using the aforementioned standard data types:

int x = 5;
int a = x;
float y = 9.87; 
float y2 = 10.76f;  // optional 'f' suffix on float literal
float b = y;
double yy = 123456.78;
double c = yy;
char z = 'Z';
char d = z;
bool test = true;
bool e = test;
bool f = !test;

Reviewing the previous fragment of code, note that a variable can be assigned a literal value, such as int x = 5; or that a variable may be assigned the value or contents of another variable, such as int a = x;. These examples illustrate this ability with various standard data types. Note that for the bool type, the value can be set to true or false, or to the opposite of one of those values using ! (not).

Variables and array basics

Arrays can be declared of any data type. The array name represents the starting address of the contiguous memory associated with the array’s contents. Arrays are zero-based in C++, meaning they are indexed starting with array element[0] rather than array element[1]. Most importantly, range checking is not performed on arrays in C++; if you access an element outside the size of an array, you are accessing memory belonging to another variable, and your code will likely fault very soon.

Let’s review some simple array declarations (some with initialization), and an assignment:

char name[10] = "Dorothy"; // size is larger than needed
float grades[20];  // array is not initialized; caution!
grades[0] = 4.0;  // assign a value to one element of array
float scores[] = {3.3, 4.3, 4.0, 3.7}; // initialized array

Notice that the first array, name, contains 10 char elements, which are initialized to the seven characters in the string literal "Dorothy", followed by the null character ('\0'). The array currently has two unused elements at the end. The elements in the array can be accessed individually using name[0] through name[9], as arrays in C++ are zero-based. Similarly, the array above, which is identified by the variable grades, has 20 elements, none of which are initialized. Any array value accessed prior to initialization or assignment can contain any value; this is true for any uninitialized variable. Notice that just after the array grades is declared, its 0th element is assigned a value of 4.0. Finally, notice that the array of float, scores, is declared and initialized with values. Though we could have specified an array size within the [] pair, we did not – the compiler is able to calculate the size based upon the number of elements in our initialization. Initializing an array when possible (even using zeros), is always the safest style to utilize.

Arrays of characters are often conceptualized as strings. Many standard string functions exist in libraries such as <cstring>. Arrays of characters should be null-terminated if they are to be treated as strings. When arrays of characters are initialized with a string of characters, the null character is added automatically. However, if characters are added one by one to the array via assignment, it would then be the programmer’s job to add the null character ('\0') as the final element in the array.

In addition to strings implemented using arrays of characters (or a pointer to characters), there is a safer data type from the C++ Standard Library, std::string. We will understand the details of this type once we master classes in Chapter 5, Exploring Classes in Detail; however, let us introduce string now as an easier and less error-prone way to create strings of characters. You will need to understand both representations; the array of char (and pointer to char) implementations will inevitably appear in C++ library and other existing code. Yet you may prefer string in new code for its ease and safety.

Let’s see some basic examples:

// size of array can be calculated by initializer
char book1[] = "C++ Programming"; 
char book2[25];  // this string is uninitialized; caution!
// use caution as to not overflow destination (book2)
strcpy(book2, "OO Programming with C++"); 
strcmp(book1, book2);
length = strlen(book2);
string book3 = "Advanced C++ Programming";  // safer usage
string book4("OOP with C++"); // alt. way to init. string
string book5(book4); // create book5 using book4 as a basis

Here, the first variable book1 is declared and initialized to a string literal of "C++ Programming"; the size of the array will be calculated by the length of the quoted string value plus one for the null character ('\0'). Next, variable book2 is declared to be an array of 25 characters in length, but is not initialized with a value. Next, the function strcpy() from <cstring> is used to copy the string literal "OO Programming with C++" into the variable book2. Note that strcpy() will automatically add the null-terminating character to the destination string. On the next line, strcmp(), also from <cstring>, is used to lexicographically compare the contents of variables book1 and book2. This function returns an integer value, which can be captured in another variable or used in a comparison. Lastly, the function strlen() is used to count the number of characters in book2 (excluding the null character).

Lastly, notice that book3 and book4 are each of type string, illustrating two different manners to initialize a string. Also notice that book5 is initialized using book4 as a basis. As we will soon discover, there are many safety features built into the string class to promote safe string usage. Though we have reviewed examples featuring two of several manners to represent strings (a native array of characters versus the string class), we will most often utilize std::string for its safety. Nonetheless, we have now seen various functions, such as strcpy() and strlen(), that operate on native C++ strings (as we will inevitably come across them in existing code). It is important to note that the C++ community is moving away from native C++ strings – that is, those implemented using an array of (or pointer to) characters.

Now that we have successfully reviewed basic C++ language features such as comment styles, variable declarations, standard data types, and array basics, let’s move forward to recap another fundamental language feature of C++: basic keyboard input and output using the <iostream> library.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon