SlideShare una empresa de Scribd logo
1 de 15
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Similar a C++primer

Similar a 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
 

Último

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 

Último (20)

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..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