Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

You're reading from   Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT] A practical, in-depth guide to implementing object-oriented design principles to create robust code

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781804613900
Length 594 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dorothy R. Kirk Dorothy R. Kirk
Author Profile Icon Dorothy R. Kirk
Dorothy R. Kirk
Arrow right icon
View More author details
Toc

Table of Contents (30) Chapters Close

Preface 1. Part 1: C++ Building Block Essentials
2. Chapter 1: Understanding Basic C++ Assumptions FREE CHAPTER 3. Chapter 2: Adding Language Necessities 4. Chapter 3: Indirect Addressing – Pointers 5. Chapter 4: Indirect Addressing – References 6. Part 2: Implementing Object-Oriented Concepts in C++
7. Chapter 5: Exploring Classes in Detail 8. Chapter 6: Implementing Hierarchies with Single Inheritance 9. Chapter 7: Utilizing Dynamic Binding through Polymorphism 10. Chapter 8: Mastering Abstract Classes 11. Chapter 9: Exploring Multiple Inheritance 12. Chapter 10: Implementing Association, Aggregation, and Composition 13. Part 3: Expanding Your C++ Programming Repertoire
14. Chapter 11: Handling Exceptions 15. Chapter 12: Friends and Operator Overloading 16. Chapter 13: Working with Templates 17. Chapter 14: Understanding STL Basics 18. Chapter 15: Testing Classes and Components 19. Part 4: Design Patterns and Idioms in C++
20. Chapter 16: Using the Observer Pattern 21. Chapter 17: Applying the Factory Pattern 22. Chapter 18: Applying the Adapter Pattern 23. Chapter 19: Using the Singleton Pattern 24. Chapter 20: Removing Implementation Details Using the pImpl Pattern 25. Part 5: Considerations for Safer Programming in C++
26. Chapter 21: Making C++ Safer 27. Assessments 28. Index 29. Other Books You May Enjoy

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.

You have been reading a chapter from
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]
Published in: Sep 2022
Publisher: Packt
ISBN-13: 9781804613900
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime