An Incomplete C++ Primer

            University of Wyoming MA 5310

                  Professor Craig C. Douglas

http://www.mgnet.org/~douglas/Classes/na-sc/notes/C++Primer.pdf
C++ is a legacy programming language, as is other languages such as

                     Language        First appeared
                     Fortran         mid 1950’s
                     C               1970
                     Pascal          mid 1970’s
                     Modula 2        late 1970’s
                     Java            1990’s
                     C#              2000’s

and others. All of these languages

  • require a significant learning curve,
  • are easy to make mistakes in that are hard to find, and
  • are hard for others to decode (in large part because programmers
    fail to adequately comment codes or use badly named data
    variables).
  • exist to manipulate data using algorithms.


                                     2
3
Textbook useful hints (by page)

  •   10-36: basics
  •   87-97: arrays
  •   108-110: switch statements
  •   126-127: compound assignment
  •   128-138: classes
  •   141: cerr

MPI (by page)

  • 71-80: basics
  • 651-676: the works




                                     4
hello-simple.cpp

A simple first program is the hello, world program:

    // my first program in C++

    #include <iostream>
    using namespace std;

    int main (int argc, char** argv)   /* command line argument info */
    {
      cout << "Hello World!n";        // cout is standard character output
      return 0;
    }

argc is the number of arguments.

argv is a pointer to an array of character pointers that hold each of the arguments
given to the program when it runs.



                                                  5
Compile the file with g++, e.g.,

    g++ hello-simple.cpp –o hello-simple

Run the program with

    ./hello-simple

Some people like to add an extension .exe on executables. Tastes vary.

g++ is available on Linux and OS X systems easily. On Windows, you can
install it natively or after installing Cygwin (or Cygwin/X is better).




                                       6
Major parts of C++

  • Data types
      o Integer: int, short, short int, long, long int
      o Floating point: float, double, long double
      o Character: char
      o User defined
  • Classes
      o A container for functions (called methods) about complicated data
        structures with public, protected, and private data.
      o Classes can be combined through inheritance to be quite complicated.
  • Templates
      o A mechanism to define a class for a wide variety of data instead of
        statically defined data, e.g., define a vector class for int, float, double
        with a single source code. Which data type is actually used is
        determined when a class is used in a program declaration. Yikes.
  • Functions
      o Independent programs that implement algorithms.


                                          7
Data types

 Type          Subtype                  Size        Description
 Integer       int                      32 or 64    standard sized
               long or long int         32 or 64    bigger is better
               short or short int       16 or 32    Legacy
 Floating      float                    32          single precision
 Point         double                   64          double precision
               long double              128         quad precision
 Character     char                     8 or 16     single character

Arrays

  char name[100];              // 100 characters, indexed 0-99
  char me[] = “Craig Douglas”; // array size computed by compiler
  double matrix[10][20];       // 10 rows, 20 columns




                                    8
Functions

  Output + Function name ( Arguments )


Pointers and References

  char* who;

  who = me;
  cout << who[0] << endl;                // endl = end of line (‘n’)
  who[0] = ‘c’;
  who[6] = ‘d’;
  cout << who << endl;                   // me is now in lower case

  who = name;
  cout << who[0] << who[1] << endl;      // 1st 2 characters



                                  9
References are used in function declarations and are similar to pointers:

    double inner_product( double& x, double& y, int len ) {

         double ip; // return value

         for( int i = 0, ip = 0.0; i < len; i++ )        // 0 <= i < len
               ip += ( x[i] * y[i] );                    // for loop’s one statement

         return ip;                                      // or just ip;
         }

Here are lots of new things: a for loop with a local variable definition, an
increment operator, and a complicated assignment statement inside the loop.

References (double& x) differ from pointers (double* x) only that the data in a
reference variable will not change. In the inner_product function, neither x nor y
will change, so they can be reference variables. Compilers can do better
optimizations on read only variables that on ones that can be changed.



                                                    10
Classes

Two distinct parts should be defined:

  1. A header file with declarations and method (function) headers.
  2. An implementation file that is compiled.

The header file should have the following sections:

  • private: all hidden variables and members are declared here.
  • protected: only classes declared as a friend are declared here.
  • public: members that can be accessed by anyone.
      o Constructors, the destructor, and copy members should be defined.
      o Access members and algorithmic members should be defined.




                                        11
A sample header file for a class hello is hello.h:

    #ifndef H_class_hello
    #define H_class_hello

    class hello {

      private:

         char greeting[100];

      public:

         hello();                          // constructor, no arguments
         hello(const char*);               // constructor, 1 argument (greeting)
         virtual ~hello();                 // destructor
         hello(hello& the_other_hello);    // copy constructor
         void set_greeting(const char*);   // set greeting
         void print_greeting();            // print greeting
    };
    #endif




                                               12
The implementation file, hello.cpp, could be as simple as

    #include "hello.h"

    #include <iostream>
    #include <string>
    using namespace std;

    hello::hello() { char ini = 0; set_greeting(&ini); }

    hello::hello(const char* msg) { set_greeting(msg); }

    hello::~hello() { }

    hello::hello(hello& the_other_hello) {
      hello(the_other_hello.greeting); }

    void hello::set_greeting(const char* msg) { strcpy(greeting, msg); }

    void hello::print_greeting() { cout << greeting << endl; }

You should study one of the classes in the textbook’s cdrom disk.


                                                  13
Compound Statements

C++ has many compound statements, including
 • if ( clause ) statement else if (clause ) statement … else (clause ) statement
      o else if and else are optional
      o many times statement is actually { statements }
 • for( initialize ; stopping condition ; updates at end of loop ) statement
      o initilize can be multiple items separated by commas
      o stopping condition is anything appropriate inside an if clause
      o updates are comma separated items
      o usually there is only one item, not multiple
 • while ( true condition ) statement
      o true condition is anything appropriate inside an if clause
 • switch ( variable ) { case value: statements break … default: statements }
      o multiple case statements can occur without a statement between them
      o default is optional
      o remember the break or the computer will continue into the next case
         (unless this is desired)


                                        14
One of C++’s strengths and weakness is the ability to overload operators. A very
good online source of information about how overload any operator in C++ is
given at the URL

    http://www.java2s.com/Tutorial/Cpp/0200__Operator-
    Overloading/Catalog0200__Operator-Overloading.htm

C++ has a Template mechanism that allows classes to be automatically defined
for different data types. There is even a Standard Template Library (STL) that
covers many useful template types.

Useful tutorials can be found at

  • http://www.cplusplus.com/doc/tutorial/
  • http://www.cplusplus.com/files/tutorial.pdf
  • http://www.java2s.com/Tutorial/Cpp/CatalogCpp.htm




                                       15

C++primer

  • 1.
    An Incomplete C++Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/Classes/na-sc/notes/C++Primer.pdf
  • 2.
    C++ is alegacy programming language, as is other languages such as Language First appeared Fortran mid 1950’s C 1970 Pascal mid 1970’s Modula 2 late 1970’s Java 1990’s C# 2000’s and others. All of these languages • require a significant learning curve, • are easy to make mistakes in that are hard to find, and • are hard for others to decode (in large part because programmers fail to adequately comment codes or use badly named data variables). • exist to manipulate data using algorithms. 2
  • 3.
  • 4.
    Textbook useful hints(by page) • 10-36: basics • 87-97: arrays • 108-110: switch statements • 126-127: compound assignment • 128-138: classes • 141: cerr MPI (by page) • 71-80: basics • 651-676: the works 4
  • 5.
    hello-simple.cpp A simple firstprogram is the hello, world program: // my first program in C++ #include <iostream> using namespace std; int main (int argc, char** argv) /* command line argument info */ { cout << "Hello World!n"; // cout is standard character output return 0; } argc is the number of arguments. argv is a pointer to an array of character pointers that hold each of the arguments given to the program when it runs. 5
  • 6.
    Compile the filewith g++, e.g., g++ hello-simple.cpp –o hello-simple Run the program with ./hello-simple Some people like to add an extension .exe on executables. Tastes vary. g++ is available on Linux and OS X systems easily. On Windows, you can install it natively or after installing Cygwin (or Cygwin/X is better). 6
  • 7.
    Major parts ofC++ • Data types o Integer: int, short, short int, long, long int o Floating point: float, double, long double o Character: char o User defined • Classes o A container for functions (called methods) about complicated data structures with public, protected, and private data. o Classes can be combined through inheritance to be quite complicated. • Templates o A mechanism to define a class for a wide variety of data instead of statically defined data, e.g., define a vector class for int, float, double with a single source code. Which data type is actually used is determined when a class is used in a program declaration. Yikes. • Functions o Independent programs that implement algorithms. 7
  • 8.
    Data types Type Subtype Size Description Integer int 32 or 64 standard sized long or long int 32 or 64 bigger is better short or short int 16 or 32 Legacy Floating float 32 single precision Point double 64 double precision long double 128 quad precision Character char 8 or 16 single character Arrays char name[100]; // 100 characters, indexed 0-99 char me[] = “Craig Douglas”; // array size computed by compiler double matrix[10][20]; // 10 rows, 20 columns 8
  • 9.
    Functions Output+ Function name ( Arguments ) Pointers and References char* who; who = me; cout << who[0] << endl; // endl = end of line (‘n’) who[0] = ‘c’; who[6] = ‘d’; cout << who << endl; // me is now in lower case who = name; cout << who[0] << who[1] << endl; // 1st 2 characters 9
  • 10.
    References are usedin function declarations and are similar to pointers: double inner_product( double& x, double& y, int len ) { double ip; // return value for( int i = 0, ip = 0.0; i < len; i++ ) // 0 <= i < len ip += ( x[i] * y[i] ); // for loop’s one statement return ip; // or just ip; } Here are lots of new things: a for loop with a local variable definition, an increment operator, and a complicated assignment statement inside the loop. References (double& x) differ from pointers (double* x) only that the data in a reference variable will not change. In the inner_product function, neither x nor y will change, so they can be reference variables. Compilers can do better optimizations on read only variables that on ones that can be changed. 10
  • 11.
    Classes Two distinct partsshould be defined: 1. A header file with declarations and method (function) headers. 2. An implementation file that is compiled. The header file should have the following sections: • private: all hidden variables and members are declared here. • protected: only classes declared as a friend are declared here. • public: members that can be accessed by anyone. o Constructors, the destructor, and copy members should be defined. o Access members and algorithmic members should be defined. 11
  • 12.
    A sample headerfile for a class hello is hello.h: #ifndef H_class_hello #define H_class_hello class hello { private: char greeting[100]; public: hello(); // constructor, no arguments hello(const char*); // constructor, 1 argument (greeting) virtual ~hello(); // destructor hello(hello& the_other_hello); // copy constructor void set_greeting(const char*); // set greeting void print_greeting(); // print greeting }; #endif 12
  • 13.
    The implementation file,hello.cpp, could be as simple as #include "hello.h" #include <iostream> #include <string> using namespace std; hello::hello() { char ini = 0; set_greeting(&ini); } hello::hello(const char* msg) { set_greeting(msg); } hello::~hello() { } hello::hello(hello& the_other_hello) { hello(the_other_hello.greeting); } void hello::set_greeting(const char* msg) { strcpy(greeting, msg); } void hello::print_greeting() { cout << greeting << endl; } You should study one of the classes in the textbook’s cdrom disk. 13
  • 14.
    Compound Statements C++ hasmany compound statements, including • if ( clause ) statement else if (clause ) statement … else (clause ) statement o else if and else are optional o many times statement is actually { statements } • for( initialize ; stopping condition ; updates at end of loop ) statement o initilize can be multiple items separated by commas o stopping condition is anything appropriate inside an if clause o updates are comma separated items o usually there is only one item, not multiple • while ( true condition ) statement o true condition is anything appropriate inside an if clause • switch ( variable ) { case value: statements break … default: statements } o multiple case statements can occur without a statement between them o default is optional o remember the break or the computer will continue into the next case (unless this is desired) 14
  • 15.
    One of C++’sstrengths and weakness is the ability to overload operators. A very good online source of information about how overload any operator in C++ is given at the URL http://www.java2s.com/Tutorial/Cpp/0200__Operator- Overloading/Catalog0200__Operator-Overloading.htm C++ has a Template mechanism that allows classes to be automatically defined for different data types. There is even a Standard Template Library (STL) that covers many useful template types. Useful tutorials can be found at • http://www.cplusplus.com/doc/tutorial/ • http://www.cplusplus.com/files/tutorial.pdf • http://www.java2s.com/Tutorial/Cpp/CatalogCpp.htm 15