Hour 19. Programming with C and C++

C is one of those programming languages that most programmers never predicted would take off. Designed as a highly efficient, somewhat cryptic language used to write an operating system named UNIX, C is a language designed by systems programmers. In the late 1980s, the same decade after its primary release, virtually every program on the store shelves was written in C. C, followed by its successor C++, quickly replaced the popular Pascal language in the 1980s and despite a much broader set of programming languages available today for different development jobs, C and C++ still remain viable programming choices. C’s impact on the programming world cannot be stressed enough.

C++ is considered by many to be a better language than C. C++ offers full support for object-oriented programming (OOP). Whereas you work with objects in Visual Basic, the Visual Basic language is not a true OOP language. You’ll learn in this hour how and why C++ provides strong OOP support and how the mechanics of C++ provide for more flexible, maintainable, and efficient programming than its predecessor, C.

The highlights of this hour include

Image Understanding why C is so efficient

Image Recognizing C commands and operators

Image Outputting with C’s printf() function

Image Using C++ to build on C programming skills

Image Using C++ classes

Image Using inheritance to decrease programming time

Introducing C

C is highly efficient and C’s developers required that efficiency because until C, programmers used assembly language, a language just above the machine language level, to write operating systems. Only assembly language had the efficiency needed for systems programs. C brought the advantage of a higher level language to the table when developers used C for operating systems. Along with the efficiency of a low-level language, C has the high-level-language advantage of being more maintainable and programmers were more easily able to update the operating system and produce accurate code. Assembly language doesn’t lend itself very well to proper program maintenance.

To achieve its efficiency, C does have one drawback that other high-level languages don’t: C is more cryptic than most other programming languages. Its cryptic nature comes in the form of a huge collection of operators and a small number of keywords. Table 19.1 lists C’s keywords. In the standard C language, there are only 32 keywords, which is an extremely small number compared to other languages, such as Java and PHP.

Image

TABLE 19.1 32 supported C command keywords


Caution

Notice that C’s keywords all appear in lowercase. C’s built-in functions also require lowercase names. C is case sensitive so if you use an uppercase letter anywhere inside a keyword or function, your program will not compile properly.


You should recognize some of C’s commands because the JavaScript language that you learned about at the beginning of this tutorial borrows heavily from C and C++.

C has more operators than any other programming language, with the exception of the scientific APL language that is rarely, if ever, used anymore. Of course, languages derived from C, such as Java and C++, often have as many or more operators than C. Because you have already studied Java, you understand many of C’s operators.

What You Need for C and C++ Programming

To program in C, you need a C compiler. Almost any C compiler you use today is a C++ compiler as well. Therefore, you get two languages for one, although C++ is really just an extension of the C language. In the early days, you often needed to purchase a compiler, usually from Borland or Microsoft. Now, there are a number of options available for free download. These are powerful packages that include an integrated development environment (IDE), compiler, debugger, and other helpful development tools.

If you plan on developing in multiple languages, including C (or C++), Microsoft’s development tools can be an excellent choice, as the IDE for C/C++ is similar to the one for Visual Basic and other .NET languages. Remember that developers created Visual Basic from the beginning to be a Windows programming system. C, on the other hand, began in the world of text-based computers. Therefore, nothing is embedded in the C or C++ programming languages to support a graphical interface.

Looking at C

The program required seven lines to output one simple sentence—and they say C is a more efficient language! Actually, C is an efficient language, but it will take you getting into C and writing more complex programs to really take advantage of the power of C; the language was written by programmers for programmers. With C’s compiled efficiency and power comes the responsibility to master the language and all its nuances.

Listing 19.1 contains three sets of grouping symbols: angled brackets, <>, braces, {}, and parentheses, (). Be extremely careful when typing a C program because the correct and exact symbol is important. C doesn’t handle ambiguity very well, so if you type the wrong symbol, C won’t work properly.

Using the main() Function’s Format

The cornerstone of every C program is the main() function. Because main() is a function and not a command, the parentheses after are required. A C function, just like a JavaScript function, is a section of code that does something. The main() function is required because execution of a C program always begins in its main() function. Programmers use main() to control the rest of the program. The main() function often includes a series of procedure calls.

The actual code for main(), as with all C functions (except the built-in functions whose code you never see), begins after the opening brace, {, and main() continues until the closing brace, }, where main() terminates and other functions often begin. Other sets of braces, always in pairs, may appear within a function such as main() as well.

As in JavaScript, many of C’s (and C++’s) statements end with a semicolon (;). The more you work with C, the better you’ll learn which statements require the semicolon and which don’t. Full statements require the semicolon. In Listing 19.1, the line with main() doesn’t require a semicolon because main() doesn’t terminate until the final closing brace in the last line. The brace requires no semicolon because it is a grouping character and does nothing on its own.


Note

The next few sections concentrate on the fundamental C language but the material is applicable to C++ also. C++’s strength over C is its ability for OOP as you’ll see later in this hour.


Using the #include Statement

You’ll never see #include in a list of C commands because #include is not a C command. Statements in a C program that begin with the pound sign are called preprocessor directives. The compiler analyzes the directive and, instead of compiling the statement, acts upon the statement immediately during compilation.

The #include preprocessor directive tells the compiler to insert another file that resides in source code form at the location in the program where the directive resides. Therefore, before the program is actually compiled, more code is inserted, at the programmer’s request, at the place where #include occurs. That code is compiled along with the programmer’s code.

The stdio.h file is a source code auxiliary file that helps a C program perform input/output (I/O) properly. C files that end with the .H extension are called header files as opposed to C program source code files that end with the .C filename extension. All C programs perform some kind of I/O, and the most common header file used to help C with its I/O is stdio.h. As you learn more about C, you’ll learn additional header files that can be helpful, such as the time.h header file that includes definitions that help with time and date conversions.

C Data

C supports data formats that work much like Java’s data formats. For example, C supports the following kinds of data:

Image Character

Image Integer

Image Floating point (decimal numbers)

C supports several types of integers and floating-point data such as long and short integers as well as single-precision and double-precision floating-point decimal data.

Unlike Java, C does not support a string data type. Although C has some built-in functionality to handle strings in some situations, generally the C language leaves it to the programmer and functions to handle strings. C doesn’t support an intrinsic string data type. Therefore, the only text-based data type that C supports is a single character.


Note

The fact that C doesn’t include support for a built-in string data type isn’t a huge problem because ample built-in functions are available in the language to work with string data. Also, C does allow for string literals, such as strings that you type directly in the code, just not string variables. Unlike Java, however, string data is not inherently supported in the fundamental language, which sometimes makes for some interesting programming.


Listing 19.1 included a string literal as well. String literals (remember there is no string variable) are always enclosed in quotation marks. Therefore, the following are string literals:

"C is efficient"

"3"

"443-55-9999"


Tip

Given the cryptic nature of C, you should add comments to your code as much as possible. You will need the comments when you later make changes to the program. You’ll be happy to know that the style of comments used in C is exactly the same as in JavaScript—enclose comments between /* and */ or preceded by // as shown in the statements below:

/* Ask how old the user is */
  printf("How old are you? "); // Ask for the age
  scanf(" %d", &age);    /* Ampersand required */


When you declare variables in C, you need to be more specific of the type of variable you need than in JavaScript. Consider the following section of a main() function:

main()
{
   char initial;
   int age;
   float amount;
...// more code here

}

This code declares three variables, initial, age, and amount. They hold three different types of data: a character, an integer, and a floating-point value. These variables are local to the function and cannot be used outside main(). (You can declare variables before main() and those variables would be global to the whole program, but global variables are not recommended, as you already know.)

The assignment statement works just as it does in JavaScript. You can initialize variables like this:

initial = 'G';
age = 21;
amount = 6.75;

C Functions

C is built on a foundation of functions—both those functions that you write and the functions supplied by C. The next two sections should help you understand the nature of C functions.

Using Built-In Functions

Unlike just about every other programming language in the world, C has no input or output statements. Look through Table 19.1 once more. You don’t see a print statement or anything else that might be considered an I/O statement.

C performs all its I/O through functions that your C compiler provides. By letting the compiler makers implement I/O in functions, the C language is highly portable, meaning that a C program that runs on one kind of computer should run on any other computer that is capable of running C programs. A C program written for a Macintosh will work on a PC without change, assuming that you compile the program using each computer’s own C compiler.

The printf() Output Function

The most common I/O function is the printf() function. printf() outputs data to the screen in most cases (although the programmer can route the output to other devices, if needed, through operating system options). Here is the format for printf():

printf(controlString [, data]);

The controlString determines how the output will look. The controlString will format any data values that you specify (separated by commas if more than one value is output) in the data area. Consider the following printf():

printf("Read a lot");

This printf() doesn’t include a data list of any kind. The controlString is the only argument to this printf(). When you use a string of text for the controlString value, C outputs the text directly to the screen. Therefore, the printf() produces this onscreen when the user runs the program:

Read a lot


Caution

Just like JavaScript, remember to use the character if you want output to force the cursor to the next line. If the previous printf() was followed by this printf():

printf("Keep learning");

the output would look like this:

Read a lotKeep learning

Obviously, the second printf() should have used the character like this:

printf("Keep learning ");

With , subsequent printf() output would appear on the next line.


When you print numbers and characters, you must tell C exactly how to print them. You indicate the format of numbers with conversion characters that format data. The conversion characters format data in functions such as printf() (see Table 19.2).

Image

TABLE 19.2 C’s most-used conversion characters

When you want to print a value inside a string, insert the appropriate conversion characters in the controlString. Then, to the right of the controlString, list the value you want printed. Figure 19.1 shows how a printf() can print three numbers—an integer, a floating-point value, and another integer.

Image

FIGURE 19.1 Conversion characters determine how and where the output appears.

Strings and characters have their own conversion characters as well. You don’t need %s to print strings by themselves because strings included inside the controlString that don’t have the formatting percent sign before them print exactly as you type them. Nevertheless, you might need to use %s when combining strings with other data.

The next printf() prints a different type of data value using each of the conversion characters from Table 19.2:

print("%s %d %f %c ", "Sams", 14, -8.76, 'X'),

This printf() produces this:

Sams 14 –8.760000 X

The string Sams needs quotation marks, as do all string literals, and the character X needs single quote marks, as do all characters. C formats the floating-point numbers with full precision, hence the four zeros at the end of the value. You can limit the number of places printed by using format specifiers. If the printf()’s conversion characters for the floating-point number had been %5.2, the –8.76 would have been output in five spaces, with two of those five spaces used for the decimal portion. Therefore, the following printf()

printf("%s %d %f %c ", "Sams", 14, -8.76, 'X'),

would yield this output:

Sams 14 –8.76 X


Working with Strings

Although C doesn’t support string variables, there is a way to store strings. C represents all strings with a null zero character at the end of the string. This null zero has an ASCII value of zero. When C encounters the null zero, the end of the string is reached. You never see this null zero on a string, but it is there, internally, at the closing quotation mark. You never add the null zero; C adds it.

If a string includes a 0 as part of its text, such as the following address: “190 S. Oak Road”, the embedded zero is not the null zero because the embedded zero is a regular ASCII character for zero (ASCII number 48).

Figure 19.2 shows how the string "Sams" is stored in memory as a string. The character is C’s representation for the null string. The length of a string includes the characters within the string but never includes the null zero.

Image

FIGURE 19.2 Strings always terminate with a null zero character.

C uses a character array to hold strings, including the string’s null zero. All of C’s data types can appear in their own arrays, but when a character array appears and a null zero is included at the end of the data, C treats that character array just like a string. C uses brackets instead of parentheses for array subscripts. To define a character array that will hold a ten-character string, you could declare the following array:

char month[10];   /* Defines a character array */

The month array can hold ten individual characters or a string if the string includes the null zero. Always leave room for the null zero in the array. C uses zero-based arrays, so month can hold a ten-character string in elements 0 through 9 and the null zero in element 10. You can initialize a string when you define the array like this:

char month[10] = "September"; /* Declare and initialize the string */

You can also assign the array at runtime using a special strcpy() function like this:

strcpy(month, "September");  /* Assigns September to the month array */

To use strcpy(), you must include the header file named string.h in the same area of the program where you include stdio.h.



Caution

The only data printf() doesn’t format is string data. Therefore, if you use printf() to print anything other than a single string, you must supply a conversion code.


The scanf() Input Function

Getting keyboard input is much more difficult than producing output on the screen. Use scanf() to accept keyboard input. scanf() is fairly simple now that you understand printf() but scanf() does behave strangely at times. Here is the format for scanf():

scanf(controlString [, data]);

Understand the following rule and scanf() should work for you every time:

Prefix each variable inside the scanf() with an ampersand unless that variable is an array.

Therefore, the following scanf() gets an age value entered by the user:

scanf(" %d", &Age);


Caution

Do you see the blank before the %d in scanf()’s controlString? Always include the blank because the input of values works better with the blank.


The following scanf() gets the user’s first name into a character array as a result of the user following the prompting printf():

printf("What is your first name? ");
scanf(" %s", name);  /* Get the name */

The scanf() function is a mirror-image function to printf(). Often, you will write programs that ask the user for values with a printf() and get those values with scanf(). When your program gets to scanf(), C stops and waits for the user to type values. The variables listed inside scanf() (following the controlString argument) will accept whatever the user types and scanf() quits receiving input when the user presses Enter.


Caution

When the user types a space, scanf() also stops getting input! Therefore, scanf() is good for getting only one word at a time in a string.


Despite its problems, scanf() is useful to learn early in your C tutorial so you can practice getting user input. There are many other ways to get user input in C and C++, and often they work better than scanf(), but scanf()’s similarity to the simpler printf() makes scanf() an acceptable keyboard-input function for beginners.

Writing General Program Functions

As with a JavaScript program’s collection of functions and event procedures, C programs are modular and are comprised of many functions. Although you can put all of a C program’s code in the main() function, main() was intended to be used as a controlling function for the rest of the program. Listing 19.3 illustrates the outline of a C program that has proper form.

LISTING 19.3 Use main() to control the rest of the program.


#include <stdio.h>
main()
{
  getNums();   /* Get a list of numbers */
  sortNums();  /* Sort the numbers */
  printNums(); /* Print the list */
  return 0;    /* End the program */
}
getNums()
{
  /* Body of function goes here
     that gets a list of values
     from the user */
}
sortNums()
{
  /* Body of function goes here
     that sorts the values */
}
printNums()
{
  /* Body of function goes here
     that prints the values */
}


The main() function is composed of a series of function calls to three separate procedures. (The code bodies of the procedures are not included in this example.) The main() function, and hence the entire running program, terminates when the return 0; statement is reached. The return often appears at the end of a function when the function is returning a value to the calling function. The main() function is returning a 0 to the operating system. Zero is a standard return value that the operating system can check.

C Operators

C’s collection of operators matches those you learned in JavaScript. For example, the plus sign works exactly as it does in JavaScript. In addition, C supports the increment and decrement operators, ++ and --, that add and subtract one from whatever variable you apply them to. The following statements each add one to the variables a, b, and c:

a++;
b++;
c++;

The following statements decrease a, b, and c by one:

a--;
b--;
c--;

C Control Statements Mimic JavaScript

Actually, C came first (just not in this book), so it’s accurate to state that JavaScript’s control statements mimic those of C (and C++). For example, C supports an if...else statement such as this:

if (age < 18)
  { printf("You cannot vote yet ");
    yrs = 18 – age;
    printf("You can vote in %d years. ", yrs);
  }
else
  {
    printf("You can vote. ");
  }

C also supports several kinds of looping statements that use the relational operators. For example, the following code shows a while loop that continues as long as the relational expression evaluates to true:

while (amount < 25)
  {
    printf("Amount is too small. ");
    wrongVal++;   /* Keep track of number of problems */
    printf("Try again... What is the new amount? ");
    scanf(" %d", &amount);
  }

Learning C++

Much of a C++ program looks like pure C code, which it is. The C++ language introduces some new language elements, but the keywords and structure are similar to C. Most of C++’s change over C is a result of injecting OOP technology into C. The primary differences between C and C++ don’t lie in commands and keyword differences but rather in how the language supports the use of objects.

C programs use the .c filename extension, and C++ programs use the .cpp filename extension. Not all C++ compilers support programming in the Windows environment, but most PC-based C++ compilers sold today do provide full Windows programming support, including the support for a visual interface such as a toolbox with controls, just as Visual Basic provides.

Object Terminology

You learned some about OOP in Part III, “Object-Oriented Programming with Java,” earlier in this tutorial. OOP is laden with terminology that might seem daunting at first. The actual implementation of OOP is fairly easy to understand and with your quick introduction, you will already be somewhat acquainted with terms such as these:

Image Abstraction—The internals of an object do not always have to be known by the programmer to use an object.

Image Class—The definition of a related group of objects.

Image Inheritance—The ability to create a new class of objects from an existing class. By inheriting a new class of objects, you can create new objects with new behaviors and characteristics based on existing objects and classes.

Image Message—A command that acts on specific objects as opposed to the other language commands that are not tied to specific objects.

Image Object—A collection of characteristics and behaviors, perhaps even two or more variables treated as a single unit, that appears in OOP programs.

Image Polymorphism—A name given to the ability of different objects to respond differently to the same commands (called messages).

Image Reuse—The ability of the language to utilize objects defined in other programs.

Fundamental Differences Between C and C++

Some of the new language features that C++ provides over C have nothing directly to do with OOP. The following sections preview some of the non-OOP language differences that you’ll find between C and C++.

Name Differences

Some differences between C and C++ are simple changes. For example, instead of C’s #include <stdio.h> directive, C++ programs almost always include the following directive:

#include <iostream>

As with the C header files, C++ programmers will include many other header files in addition to iostream.h, but iostream.h is the most commonly included file. iostream.h is the header file that defines basic input and output.

I/O Differences

C++ includes several new operators. The two most common C++ operators are >> for output (the insertion operator) and << (the extraction operator). These operators are usually combined with the two stream objects cout and cin. cout always represents an output device and defaults to the screen. cin always represents an input device and defaults to the keyboard. You can redirect cout and cin to other devices through the operating system and through compilers such as Visual C++ if you ever have the need. Your program considers these stream objects to be nothing more than a series of data values that are being input or output.

A few examples will quickly show you how to combine the insertion and the extraction operators with stream objects. The following statement sends a string and a number to the screen (typically the output stream goes to the screen although you can change that destination to a different device):

cout << "Here is the total: " << 1000.00;

If you want to write several lines of output, you can by embedding the newline character in the output stream. The following line

cout << "Line 1" << ' ' << "Line 2" << ' ' << "Line 3" << ' ';

produces this output:

Line 1
Line 2
Line 3


Tip

Generally, C++ programmers don’t use the newline character, , at the end of a statement with cout. They use a special object called endl, which not only produces a newline character but also empties the output buffer if you send data to a device that buffers output, such as a printer. Therefore, the following statement would be more likely than the one shown before this tip:

cout << "Line 1" << ' ' << "Line 2" << ' ' << "Line 3" << endl;


C++ combines the cin input stream with the >> extraction object to support keyboard input. As with scanf(), keyboard-based input with C++ is fairly simple to understand and implement, but C++’s input capabilities are limited when you use cin >> just to start with a way to get keyboard input quickly. However, keep in mind that more advanced and better input methods exist that you will master if you pursue the C++ language.

To get a keyboard value into an integer variable named intAge, you could use the following:

cin >> intAge;

Of course, you would probably prompt the user first with a cout so the I/O would more likely look like this:

cout << "How old are you? ";
cin >> intAge;    // Get the age

Introducing C++ Objects

To declare a C++ object you first must declare a class. A class is not an object but rather a description of an object. The C++ language includes the class keyword that you use to define a class.

Consider the following class declaration:

class Person {
  char strLastName[25];
  int  intAge;
  float flSalary;
};

The class name is Person. The class is said to have three members. The member names are strLastName, intAge, and flSalary. This class, therefore, describes objects that contain three members. Individually, each member could be considered a separate variable, but taken together (and C++ will always consider the members to be part of the class) the members form the class. The members are not objects but parts of objects that you can define with this class.


Caution

Remember, a class is a description of an object but not the object itself. In a way, int is a keyword that defines a class; int is a data type that describes a type of numeric value or variable. Only after you define integer variables do you have an integer object.


Declaring Object Variables

C++, without your help, would have no idea what the Person class would be because Person is not some internal class native to C++. Therefore, the multilined class statement shown earlier tells C++ exactly what the class’s characteristics are like. After you define the class, you then can declare variables, or, more accurately, objects of the class. The following statement declares a Person object called Mike:

Person Mike;   // Declares an instance of the Person class

Figure 19.3 shows what the object (or variable or instance of the class) looks like. The object named Mike is a three-part object. The characteristics are as follows: Mike is an object that begins with a 25-character array, followed by an integer, followed by a floating-point value.

Image

FIGURE 19.3 The object named Mike internally contains three members.

All Person objects that you declare from the Person class will look like Mike, but they will have different names just as integer variables in a program have different names. In addition, the objects will have local or global scope depending on where you declare them.


Tip

Generally, programmers place the class definition globally or even stored in a header file that they include in subsequent programs. After the class definition appears globally (such as before the main() procedure), any place in the rest of the program can declare object variables from the class. The variables might be global, but they will probably be local if the programmer follows the suggested standards and maintains only local variables to a procedure. As with any variables, you can pass object variables between procedures as needed.


Any place in the program can declare additional object variables. The following statement would declare three additional objects that take on the characteristics of the Person class:

Person Judy, Paul, Terry;

Accessing Members

You’ll use the dot operator (a period) to access members in an object. For example, the following assignment stores a value in the Mike object’s intAge member:

Mike.intAge = 32;  // Initialize the member named age

As long as you qualify the member name with the object name, C++ knows which object to assign to. Therefore, if several Person objects are declared in the program, the object name before the member informs the program exactly which object member you want to initialize. Anywhere you can use a variable, you can use a member name as long as you qualify the name with the object. For example, you cannot directly assign a string literal to a character array in C++ (or in C), but you can use the strcpy() function like this:

strcpy(Mike.strLastName, "Johnson");  // Assign the name

You could print one of the members like this:

cout << Mike.intAge;  // Display the age

If you wanted to print the three members, you might do so like this:

cout << Mike.strLastName << ", " << Mike.intAge << ", " << Mike.flSalary << endl;

Adding Behavior to Objects

Until now, you’ve only seen how to add characteristics to a class by defining the class members. You can also define the class behaviors. The behaviors describe what objects in the class can do. Adding behaviors to a class requires much more time to cover than the rest of this hour will allow. Nevertheless, by seeing an example or two of a class with defined behavior, you will begin to see how objects begin to take on a life of their own, something that simple variables cannot do.

The following Person class definition is more complete than the previous one because it defines not only the characteristics (the members and their data types) but also the behaviors (called member functions):

class Person {
  char strLastName[25];
  int  intAge;
  float flSalary;
  // Member functions appear next
  void dispName( void )
    { cout << "The last name is ";
      cout << strLastName << endl;
    }
  void compTaxes(float taxRate)
    {  float taxes;
       taxes = taxRate * flSalary;
       cout << "The taxes are ";
       cout << taxes << endl;
    }
  char * getName( void )
    { return strLastName; }
  int getAge ( void )
    { return intAge; }
  float getSalary ( void )
    { return flSalary; }
};

Just as a member can be an instance of a variable, a member can also be a function. The embedded function, the member function, applies only to objects declared from this class. In other words, only Person objects behave exactly this way but those Person objects can perform the operations defined by the member functions. In a way, the objects are smart; they know how to behave, and the more member functions you supply, the more the objects know how to do.

Many programmers elect to use function declarations (the declaration, or first line of a function, is called the function’s prototype) in the class statement, but then define the actual function code later. By placing function prototypes after the class itself, you keep the class cleaner like this:

class Person {
  char strLastName[25];
  int  intAge;
  float flSalary;
  // Member functions appear next
  void dispName( void );
  void compTaxes(float taxRate);
  char [] getName( void );
  int getAge ( void );
  float getSalary ( void );
};

void Person::dispName( void )
  { cout << "The last name is ";
    cout << strLastName << endl;
  }
void Person::compTaxes(float taxRate)
  {  float taxes;
     taxes = taxRate * flSalary;
     cout << "The taxes are ";
     cout << taxes << endl;
  }
char [] Person::getName( void )
  { return strLastName; }
int Person::getAge ( void )
  { return intAge; }
float Person::getSalary ( void )
  { return flSalary; }

The class statement is more compact because only prototypes appear in the definition and not member function code. The member function code could appear elsewhere in the program or, more likely, would be included from a file you or another programmer created that contains the member functions you need to call. Notice that if you place the function’s definition later in the program, you must preface the definition with the class name followed by the :: operator. The class name qualifies the function because different classes may have member functions with the same name as other classes in the program.

Before explaining how to apply the member functions to objects, you need to understand how scope affects objects and their member functions.

Working with Class Scope

As you know, the class statement defines a class and its members and member functions. However, special consideration must be given to the scope of individual data and function members. In the previous class definition, all members were private, meaning no code outside the class could access the data members. You can override the default privatization of members by using special public and private qualifiers to make the class available to code.

Consider this modified Person class definition (the member function code is omitted for brevity):

class Person {
  char strLastName[25];
  int  intAge;
  float flSalary;
  // Member functions appear next
public:
  void dispName( void );
  void compTaxes(float taxRate);
  char [] getName( void );
  int getAge ( void );
  float getSalary ( void );
};

All members are considered to be private unless you precede them with the public keyword. All members before public are private but you can optionally place private: before the first member so other programmers know your intention is that the class members up to the next public keyword remain private. All members (both data members and function members) that follow public: are public.

Being private means that any program that uses the class can never access private members. This is critical for data protection that the class provides. Earlier in this hour you saw the following statement:

cout << Mike.intAge;  // Display the age

Actually, this statement will not work in the program because the program does not have access to the intAge data member. The intAge data member is private so no code outside the class can access intAge. By protecting the data members, you keep the object intact and ensure that only predefined functions available in the class can access the age. That’s why you often see member functions that begin with get as in the getAge() function shown previously. Because getAge() is in the public section of the class, any program that defines Person objects can use the getAge() function. Therefore, you cannot display intAge directly, but you can call the getAge() function like this:

cout << Mike.getAge();  // Display the age

Notice that when you apply the member function to the object, you use the dot operator just as you do for data members. Other class objects may be defined and also have functions named getAge(), so you must qualify the member function by letting the program know you want the getAge() function applied to one specific object variable in the program named Mike.

Keep in mind that complete college courses and huge texts exist that teach OOP in C++. You’re getting only an overview here, although the overview is actually rather complete. After mastering this introductory hour, you should be able to understand the early portions of a course or text on C++ much more easily.

Things to Come

Given the introduction to C++ that you’ve now had, you can better understand the advantages that C++ provides over more traditional, non-OOP languages. One of the benefits of OOP is that you can create your own operators. More accurately, you can change the way an operator works when the program uses that operator with one of your objects.

By writing special operator overloading member functions, you can make any C++ operator work on your own objects. For example, a plus sign is the addition operator that automatically works on all numeric values. The plus sign, however, cannot work on a Person object such as Mike. Therefore, if you wanted to add two Person objects together to get a total of the salaries, you could write a function that added the salaries of two or more flSalary data members. When you apply the totaling function members to objects, you can produce the total of the salaries, but you can also overload the plus sign operator so that plus works not only for two numbers but also for two Person objects like this:

totalSals = Mike + Terry;  // Possible by overloading the +

You could never ordinarily use a plus sign between two Person objects such as Mike and Terry because they are objects you created and they contain three data members of different data types. But once you overload the plus operator to add the appropriate values inside Person objects, you can add their values easily.


Note

You saw an example of operator overloading when you learned JavaScript earlier in this tutorial. When the plus sign (+) is used with two numbers in JavaScript, it adds the values, but when it is used with two strings, it concatenates them into one larger string. It’s one operator, but it can perform different jobs.


Such operator overloading means that you can simplify a program’s code. Instead of using a function to simulate a common operation, you can actually use the operator itself, applied to your own objects. The member function that describes the operator overloading determines exactly which data members are affected and used by the operation.


Note

The overloading of operators is how you can use the << and >> to input and output complete classes of objects with multiple members and even use Windows-based controls such as text boxes to receive or initiate the special I/O.


The concept of polymorphism makes the overloading of operators possible. For example, the same operator applied to an integer variable behaves much differently if you apply that operator to a class object that you define.

In addition to overloading operators, you can create your own data types. Keep in mind that a class simply defines a collection of data that is composed of data members that conform to an ordinary data type. You could, for example, create a String class whose only data member is a character array. By overloading the appropriate operators, you can make C++ behave like Java and support string-like variables.

The String class is just one example of the many classes you and others can write to support object reuse later down the road. Over time, you will build a large library of classes that you can use for future programs. As you build classes, the amount of code that you have to write should lessen and you should complete applications more quickly. In addition, as you build and debug object class libraries, your programs should become more maintainable. Using operator overloading and other OOP advantages means that your code will be less bulky. When you need an object, you will simply create one from one of your class libraries just as you add new stereo components when you want to expand your music system.

One of C++’s most productive features is inheritance. When you or someone else writes a class that you use, you are not limited to objects of that class. The C++ language supports inheritance so that you can derive new classes and create new objects that have all the benefits and features of their parent classes but with additional features as well.

Summary

Are you a C or C++ expert after one hour’s lesson? No way. Do you understand the fundamentals of C and C++? You’d be surprised at how well you now already understand the language, especially with your Java introduction earlier. You could not master OOP with C++ in one hour either, but you’ve already learned the fundamentals of how C++ works. At its most basic level, the C++ language offers language improvements over C even if you don’t use OOP. Nevertheless, when you begin to use OOP, you will learn to create classes that define objects that seem to take on a life of their own. The objects understand how to perform some duties based on their member functions and you can extend the objects through inheritance to derive new classes that you can use later.

Q&A

Q. Why is #include not a C command?

A. #include is a preprocessor directive and is not part of the C language. #include, and all other lines that begin with #, such as #define, control how C compiles a program instead of controlling the way that the C program executes.

Q. Can the programmer extend the class by adding functionality if a class does not quite contain enough power?

A. Certainly. That’s where the power of class inheritance comes into play. The programmer can include the class and then inherit a new class from the existing class. The inherited class contains all the data members and member functions of the parent class without the programmer doing anything special. Then, the programmer can add additional data members and member functions (both private and public) to the class to make the class operate as needed. Such inheritance makes the reuse and extension of objects extremely easy and should improve the efficiency of programmers as more object libraries are written and distributed.

Workshop

The quiz questions and exercises are provided for your further understanding.

Quiz

1. How is C more efficient than JavaScript?

2. What is a header file?

3. What function do all C programs begin with?

4. True or false: C supports string literals.

5. What is wrong with the following statement?

if (sales < 2500.00);
  {
    printf("You need to work harder. ");
  }

6. What included header file defines I/O in most C++ programs?

7. Where do you define an object’s data members and member functions?

8. What two operators and system objects do C++ programmers often use for input and output?

9. What OOP term allows for operator overloading?

10. How does inheritance improve a C++ programmer’s efficiency?

Answers

1. C compiles into a more efficient language than JavaScript, often because of its heavy use of operators instead of commands.

2. A header file brings in extra routines and library definitions and is brought in with the #include statement, not unlike the Java import command.

3. All C programs start with main().

4. True.

5. The semicolon should not appear after the if’s closing parentheses.

6. <iostream> defines the I/O routines for most C++ programs.

7. Define an object’s data members and member functions inside the object’s class definition.

8. C++ programmers often use cin>> and cout<< for input and output.

9. Polymorphism allows for operator overloading.

10. Programmers do not have to repeat all the code when defining inherited objects; programmers only have to write code that adds or changes functionality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.102.50