Introduction to C++

Author: Ronald S. Holland
at
Total Application Works

ronholland@sumtotalz.com





To contact us



[
HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).
  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/CPP/CPP_Introduction.html">
    Introduction to C++ Programming </a>
    </table>
    </body>
    </html>


  • Introduction to C++
  • Programs
  • Programs used to solve Tasks
  • What is a C++ Program?
  • What are program commands?
  • What is a Function?
  • So how do you get access to those prewritten/built-in functions?
  • First C++ Program
  • Definitions


    Introduction to C++

    This tutorial does not assume that you have some prior programming experience. This tutorial is intended to be an introductory discussion on C++ and programming. C++ as a programming language is widespread and can be found on nearly all computers. This tutorial will prepare you to step through a set of tutorials on C++.

    What is C++? C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs and originally named C with Classes. It was originally developed as an enhancement to the C language. It was renamed C++ in 1983. In addition, one of the enhancements C++ introduced to the C language was object-oriented programming (OOP). As we ease into C++ programming, you'll learn

    The following list outlines the tutorials we will use to introduce C++. In the rest of this tutorial will describe:
    • What makes up a Program
    • How programs are used to solve Tasks
    • Exactly what is a C++ Program to a computer
    • Exactly what are program commands
    • What makes up a function
    • How do you get access to those prewritten/built-in functions

    Programs

    A program is a set of instructions used to solve a task. More specifically, these instructions tell a computer what to do. These set of instructions are like a recipe used to make a cake; a set of computer instructions are used to make a program. To make/create a program, we do the following:

    1. Source code is created when we enter a sequence of commands into a text editor, like notepad.
    2. When we process the raw source/code with a compiler, it results in object code.
    3. Once a program is in an object code format, a link editor processes the object code to form an executable program. These steps are outlined in the following table.

       
      
          +---------------------+
          |   text editor       | Step 1: Open an Text Editor 
          +-----------+---------+
                      |
                      V
          +---------------------+
          |   source code       | Step 2: Enter raw source into Text Editor
          +-----------+---------+
                      |
                      V
          +-----------+---------+
          |      compiler       | Step 3: compiler processes file created 
          +-----------+---------+         by Text Editor that contains 
                      |                   source code
                      V
          +-----------+---------+
          |      Link Editor    | Step 4: Object code created by compiler
          +-----------+---------+         is processed by Link Editor
                      |
                      V
          +-----------+---------+
          | executable program  | Step 5: Result of link editor
          +---------------------+
       
      Figure 1: Steps taken to create an executable program


    Why do we write programs? With the aid of a computer, programs are written to solve a task. These tasks could be a game, a program to view contents on a drive e.g., Windows Explorer, or a text editor e.g., Notepad.

    Programs used to solve Tasks

    Application software consists of those programs written to perform particular tasks that are required by the users. For example, the following partial list shows programs that solve a specific task.

    • Browser - is a software application used to locate and display Web pages. Some examples of this type of software are Mozilla Firefox and Microsoft Internet Explorer.
    • Database Management System Software (DBMS) - A DBMS is the structured collection and management of data. It is a set of programs that allows you to store, modify, and access information from a database. DBMS software allows the users to store and retrieve data from databases. Examples are Oracle, MSAccess, etc.
    • Educational Software - The primary purpose of this type of software is teaching or self-learning. It has the capabilities of running tests and tracking student progress. It also has the capabilities of collaborative software. Some examples of areas touched by this type of software are:
      • Anatomy
      • Children's software
      • Dictionaries and reference
      • Environmental Education
      • Geography and Astronomy
      • Historical
      • Literacy
      • Managed learning environments
      • Mathematics
      • Music
      • Programming
      • Science
      • Simulation Games
      • Touch-Typing Instruction
      • Visual Learning and Mind Mapping
    • Enterprise Software - It is the software needed to run an organization's processes and data flow. If the organization is a retail enterprise, then it is the software needed to process and manage the enterprise's business. The customer relationship management or the financial processes in an organization are carried out by means of enterprise software. It might look like:
      • ERP (Enterprise Resource Planning) - this is a view of a company and all its parts as a synergistic connected whole, rather than small slices of independent activity.
      • CRM (Customer Relationship Management) - is a company-wide business strategy designed to reduce costs and increase profitability by solidifying customer loyalty, loyalty, and advocacy. It is a process or methodology used to learn more about customers' needs and behaviors in order to develop stronger relationships with them.
      • POS - Point of sale (POS) or checkout is the location where a sale/transaction occurs. A "checkout" refers to a POS terminal or more specifically to the hardware and/or software used for checkouts, the equivalent of an electronic cash register.
      • Business Intelligence
      • General Ledger
      • Accounts Receivable
      • Accounts Payable
      • Inventory Control
      • Manufacturing
      • Payroll
      • Human Resources
      • ecommerce connectivity
    • Information Worker Software - Individual projects within a department and individual needs of creation and management of information are handled by information worker software. Documentation tools, resource management tools and personal management systems fall under the category of this form of application software.
    • Multimedia Software - This software allows the user to create and play audio and video media. They are capable of playing media files. Real Player and Media Player are examples of this type of software include.
    • Operating Systems - The operating system is the most important program that runs on a computer. It manages the conduits that allow other programs to interface with computers peripherals. For example:
      1. Writing to disk;
      2. Displaying data on a display/monitor screen;
      3. Sending data to a printer;
      4. Reading/writing to a DVD or CD;
      Every general-purpose computer must have an operating system to run other programs. Some operating systems are:
      1. Microsoft Windows 98, ME, XP, Vista, Windows 7;
      2. Unix;
      3. Linux;
      4. IBM: OS/360, DOS/360, DOS/VS, MVS, VM/370, and TSS/370;
      All of these operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the display screen, keeping track of files and directories on the disk.
    • Presentation Software - The software that is used to display information in the form of a slide show is known as presentation software. This type of software includes three functions, namely, editing that allows insertion and formatting of text, methods to include graphics in the text and a functionality of executing the slide shows. Microsoft PowerPoint is the best example of presentation software.
    • Simulation Software - Used to simulate physical or abstract systems, simulation software finds applications in both, research and entertainment. Flight simulators and scientific simulators find a place in the list of simulation software.
    • Spreadsheet Software - Some examples of spreadsheet software are Excel, Lotus 1-2-3, and Apple Numbers. Spreadsheet software displays rows and columns of data that allow users to perform calculations on this displayed data.
    • Text Editor - is a type of program used for editing plain text files.
    • Word Processor - A word processor is a computer application used in the creation/composition, editing, formatting, and/or printing of documents. A word processor enables you to create a document, store it electronically on a disk, display it on a screen, edit it by entering commands (i.e., fonts, bold, italics, etc.) and characters from the keyboard, and print it on a printer.

    What is a C++ Program?

    What is a navigation program? A navigation Program is an easy-to-use software application that provides step-by-step directions showing the user how to get from point A to point B. If you consider that the human brain is similar to a computer, then these instructions are commands to the user providing instructions on what steps to perform next. A C++ program is a collection of commands, that tell the computer what steps to perform next. This collection of commands, written in a programming language, is usually called C++ source code, source code or just code. As previously stated, human brains are similar to computers. As humans, we run programs all the time. Our daily routines could be considered human programs. For example, look at the following routine/program.

     
    Wake up;
    Go to the bathroom;
    Wash up;
    Exercise; 
    Eat breakfast; 
    Shower; 
    Get dressed; 
    Go to work; 
    Do work/job; 
    Return home;
    Watch TV;
    Log on to the Internet;
    Read/send email;
    Go to bed;
     
    Figure 2: A human daily routine/program


    Many of us have a similar routine/program that we follow every day. These routines consist of a set of commands. We will explore some of the C++ commands in the next section.

    What are program commands?

    Commands are either "functions" or "keywords". Keywords are predefined reserved identifiers that have specified meanings/functions. Since they are predefined, they cannot be used as identifiers (variable names or function/method names) in your program. The set of rules of a language, C++ in this case, that dictate how the various parts (keywords and/or commands) of sentences go together to provide instructions for a computer is called syntax. For example, the "int a;" statement tells the compiler that variable "a" is of data type int. Some of the C++ commands are listed in the following table.

    __abstract 2 abstract __alignof Operator array
    __asm __assume __based bool
    __box 2 break case catch
    __cdecl char class const
    const_cast continue __declspec default
    __delegate 2 delegate delete deprecated 1
    dllexport 1 dllimport 1 do double
    dynamic_cast else enum enum class
    enum struct event __event __except
    explicit extern false __fastcall
    __finally finally float for
    for each, in __forceinline friend friend_as
    __gc 2 gcnew generic goto
    __hook 3 __identifier if __if_exists
    __if_not_exists initonly __inline inline
    int __int8 __int16 __int32
    __int64 __interface interface class interface struct
    interior_ptr __leave literal long
    __m64 __m128 __m128d __m128i
    __multiple_inheritance mutable naked 1 namespace
    new new __nogc 2 noinline 1
    __noop noreturn 1 nothrow 1 novtable 1
    nullptr operator __pin 2 private
    __property 2 property property 1 protected
    public __raise ref struct ref class
    register reinterpret_cast return safecast
    __sealed 2 sealed selectany 1 short
    signed __single_inheritance sizeof static
    static_cast __stdcall struct __super
    switch template this thread 1
    throw true try __try/__except,
    __try/__finally
    __try_cast 2 typedef typeid typeid
    typename __unaligned __unhook 3 union
    unsigned using declaration, using directive uuid 1 __uuidof
    value struct value class __value 2 virtual
    __virtual_inheritance void volatile __w64
    __wchar_t, wchar_t while
     
     
    Figure 3: C++ Keywords


    If keywords are the bricks, then the syntax is the mortar that forms the building blocks of the language. Then, what are functions? Below, are some of the functions listed alphabetically.

    abort() abs() acos() asin()
    atan() atexit() atof() atoi()
    atol() ceil() clock() cosh()
    ctime() div() exit() fabs()
    floor() fmod() getchar() getenv()
    isalnum() isalpha() isdigit() isgraph()
    ispunct() isspace() isupper() kbhit()
    log10() log2() log() memcmp()
    modf() pow() putchar() putenv()
    puts() rand() remove() rename()
    sinh() sqrt() srand() strcat()
    strcmp() strerror() time() tolower()
    toupper()
     
     
     
    Figure 4: C++ Functions


    Considering the functions in Figure 4, what is their purpose?

    What is a Function?

    A function is a self-contained block of code that has a name and it has a property that it is reusable/reentrant i.e. it can be executed from as many different points in a C++ program or many C++ programs as required. A function allows a number of program statements to be grouped into a unit with an addressable name. This unit can be called/invoked from other parts of a program. A function is usually created to perform a task that will be needed many times in a program or needed by many program e.g., SQRT(). An outline of a function is depicted in the following figure.

     
    #include <iostream>
    
    using namespace std;
    
    function_name( data_type parameter ) {
       needed_variables ;
       int a ;
       int b ;
    
       code line 1 ;
       code line 2 ;
       a = 9 ;  
       b = sqrt( a ) ;  
    
         ...
    
       code line n ;
    }
    
    /** **************************************
     * The main() function is the entry point 
     * that is called C++ runtime.
     *****************************************/
    int main()
    {
      lines_of_code
    }
     
    Figure 5: Outline of a Function


    The name of the function is unique in a C++ program and is global within the C++ language supplied library. This means that a function can be accessed from any location within a C++ program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing. It should be noted that C++ provides a great many common functions and keywords that you can use (see Figure 3 and/or see Figure 4).

    You may be wondering how does your program actually start? Every C++ program has one entry point/function, which is called main. This function is the entry point that is called when your program first loaded into memory. From the main function, you can also call other functions whether they you wrote them or, as previously mentioned, they are provided by the compiler.

    So how do you get access to those prewritten/built-in functions?

    To access those standard functions that come with the compiler, you include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program. Refer to Figure 5 to see an outline/template of a program written in pseudocode.

      
    #include <iostream>
    
    using namespace std;
    
    /*****************************************************
     * The main() function is the entry point that is called
     * when the program is loaded into memory.
     ****************************************************/
    int main()
    {
      cout << "This is a message from\n";
      cout << "Ronald S. Holland\n";
      cout << "         @\n";
      cout << "Sumtotalz.com\n";
      cin.get();
    }
     
    Figure 6: Outline of a Function


    Let's look at the statements in the program in Figure 6.
    1. #include <iostream.h>
        In the above statement, the "#" is called 'preprocessor' and 'include' is a keyword. "#include" is used to include header files; in this case, #include <iostream.h>. #include is a "preprocessor" directive that tells the compiler to put code from the header called iostream into our program before actually creating the executable. We gain access to many different functions, by including header files. For example, the cout function requires that we include the iostream header.
    2. using namespace std
        This statement allows this program to access the members of the std library. This line tells the compiler to use a group of functions that are part of the standard library (std). By including this line at the top of a file, you allow the program to use functions such as cout. Some of the classes in the std library are:

        Classes
        ios ios is a header file in the C++ standard library which defines several types and functions basic to the operation of iostreams.
        iostream iostream is a header file which is used for input/output in the C++ programming language.
        iomanip Provides facilities to manipulate output formatting, such as the base used when formatting integers and the precision of floating point values.
        fstream is a standard C++ library that handles reading from and writing to files either in text or in binary formats
        Sstream It is a header file that provides templates and types that enable interoperation between stream buffers and string objects. Header providing string stream classes:
        Figure 7: Some libraries in the std library


      Please note that <iostream> is but one of the many libraries that can be included.
    3. int main()
        This is the entry point to the programs that is called by C++ at run-time and when the program is loaded into memory. This line also tells the compiler that there is a function named main, and that this function, on exit, returns an integer or int. The "curly braces" ("{" and "}") signal the beginning and end of functions and other code blocks. You can think of them, as meaning BEGIN, after which there is code, and END, end of code.
    4. cout
        This member corresponds the system stdout. cout is an object of class ostream that represents the standard output stream. The cout object is used to display text (pronounced "C out"). It uses the << symbols, which are known as insertion operators, to indicate what to write to the screen. cout<< results in a function call with the text following the operator used as an argument in the cout function call. The quotes tell the compiler that we want to print the literal string as-is. The '\n' escape sequence is actually treated as a single character that stands for a newline.
    5. cin.get()
        corresponds to the cstdio stream stdin. cin is an object of class istream that represents the standard input stream. This is another function call: it reads in input and expects the user to hit the return key. When you program runs, it will open a new console window, run the program, and then close the window. This command keeps that window from closing because the program has not completed its task yet because it is waiting for the user to press the enter key. Including this line gives us time to see the program run, see any program output, and evaluate the success of the program.
    6. Upon reaching the end of main, the closing brace, our program will return the value of 0 (and integer, hence why we told main to return an int) to the operating system. This return value is important as it can be used to tell the OS whether our program succeeded or not. A return value of 0 means success and is returned automatically (but only for main, other functions require you to manually return a value), but if we wanted to return something else, such as 1, we would have to do it with a return statement:
       
      
      

    Definitions

    Compiler

    Holland's OOP Programming Design Model






HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works