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

Revisiting control structures, statements, and looping

C++ has a variety of control structures and looping constructs that allow for non-sequential program flow. Each can be coupled with simple or compound statements. Simple statements end with a semicolon; more compound statements are enclosed in a block of code using a pair of brackets {}. In this section, we will be revisiting various types of control structures (if, else if, and else), and looping constructs (while, do while, and for) to recap simple methods for non-sequential program flow within our code.

Control structures – if, else if, and else

Conditional statements using if, else if, and else can be used with simple statements or a block of statements. Note that an if clause can be used without a following else if or else clause. Actually, else if is really a condensed version of an else clause with a nested if clause inside of it. Practically speaking, developers flatten the nested use into else if format for readability and to save excess indenting. Let’s see an example:

#include <iostream>
using namespace std;   // we'll limit the namespace shortly
int main()
{
    int x = 0;
    cout << "Enter an integer: ";
    cin >> x;
    if (x == 0) 
        cout << "x is 0" << endl;
    else if (x < 0)
        cout << "x is negative" << endl;
    else
    {
        cout << "x is positive";
        cout << "and ten times x is: " << x * 10 << endl;
    }  
    return 0;
}

Notice that in the preceding else clause, multiple statements are bundled into a block of code, whereas in the if and else if conditions, only a single statement follows each condition. As a side note, in C++, any non-zero value is considered to be true. So, for example, testing if (x) would imply that x is not equal to zero – it would not be necessary to write if (x !=0), except possibly for readability.

It is worth mentioning that in C++, it is wise to adopt a set of consistent coding conventions and practices (as do many teams and organizations). As a straightforward example, the placement of brackets may be specified in a coding standard (such as starting the { on the same line as the keyword else, or on the line below the keyword else with the number of spaces it should be indented). Another convention may be that even a single statement following an else keyword be included in a block using brackets. Following a consistent set of coding conventions will allow your code to be more easily read and maintained by others.

Looping constructs – while, do while, and for loops

C++ has several looping constructs. Let’s take a moment to review a brief example for each style, starting with the while and do while loop constructs:

#include <iostream>
using namespace std;   // we'll limit the namespace shortly
int main()
{
    int i = 0;
    while (i < 10)
    {
        cout << i << endl;
        i++;
    }
    i = 0;
    do 
    {
        cout << i << endl;
        i++;
    } while (i < 10);
    return 0;
}

With the while loop, the condition to enter the loop must evaluate to true prior to each entry of the loop body. However, with the do while loop, the first entry to the loop body is guaranteed – the condition is then evaluated before another iteration through the loop body. In the preceding example, both the while and do while loops are executed 10 times, each printing values 0-9 for variable i.

Next, let’s review a typical for loop. The for loop has three parts within the (). First, there is a statement that is executed exactly once and is often used to initialize a loop control variable. Next, separated on both sides by semicolons in the center of the () is an expression. This expression is evaluated each time before entering the body of the loop. The body of the loop is only entered if this expression evaluates to true. Lastly, the third part within the () is a second statement. This statement is executed immediately after executing the body of the loop and is often used to modify a loop control variable. Following this second statement, the center expression is re-evaluated. Here is an example:

#include <iostream>
using namespace std;   // we'll limit the namespace shortly
int main()
{
    // though we'll prefer to declare i within the loop
    // construct, let's understand scope in both scenarios
    int i; 
    for (i = 0; i < 10; i++) 
        cout << i << endl;
    for (int j = 0; j < 10; j++)   // preferred declaration
        cout << j << endl;      // of loop control variable
    return 0;
}

Here, we have two for loops. Prior to the first loop, variable i is declared. Variable i is then initialized with a value of 0 in statement 1 between the loop parentheses (). The loop condition is tested, and if true, the loop body is then entered and executed, followed by statement 2 being executed prior to the loop condition being retested. This loop is executed 10 times for i values 0 through 9. The second for loop is similar, with the only difference being variable j is both declared and initialized within statement 1 of the loop construct. Note that variable j only has scope for the for loop itself, whereas variable i has scope of the entire block in which it is declared, from its declaration point forward.

Let’s quickly see an example using nested loops. The looping constructs can be of any type, but in the following, we’ll review nested for loops:

#include <iostream>
using namespace std;   // we'll limit the namespace shortly
int main()
{
    for (int i = 0; i < 10; i++) 
    {
        cout << i << endl;
        for (int j = 0; j < 10; j++)
            cout << j << endl;
        cout << "\n";
    }
    return 0;
}

Here, the outer loop will execute ten times with i values of 0 through 9. For each value of i, the inner loop will execute ten times, with j values of 0 through 9. Remember, with for loops, the loop control variable is automatically incremented with the i++ or j++ within the loop construct. Had a while loop been used, the programmer would need to remember to increment the loop control variable in the last line of the body of each such loop.

Now that we have reviewed control structures, statements, and looping constructs in C++, we can move onward by briefly recalling C++’s operators.

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 R$50/month. Cancel anytime