SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
C Basics
C BasicsC Basics
C Basics
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
java vs C#
java vs C#java vs C#
java vs C#
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
C++ language
C++ languageC++ language
C++ language
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Java 8
Java 8Java 8
Java 8
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 

Ähnlich wie C++primer

Ähnlich wie C++primer (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C tutorial
C tutorialC tutorial
C tutorial
 
PRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptxPRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptx
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorials
C tutorialsC tutorials
C tutorials
 
C programming language
C programming languageC programming language
C programming language
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
C++
C++C++
C++
 
C tutorial
C tutorialC tutorial
C tutorial
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C language updated
C language updatedC language updated
C language updated
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 

Kürzlich hochgeladen

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 

Kürzlich hochgeladen (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 

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 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. 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 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
  • 6. 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
  • 7. 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
  • 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 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
  • 11. 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
  • 12. 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
  • 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++ 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
  • 15. 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