Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

CS 6301 Lecture 2: First Program1. CS Topics of this lecture Introduce first program  Explore inputs and outputs of a program Arithmetic using.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
Introduction to C++CS-2303, C-Term Introduction to C++ CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Guide To UNIX Using Linux Third Edition
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Basic Elements of C++ Chapter 2.
Introduction to C++ Systems Programming.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Object-Oriented Programming (OOP) and C++
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
Chapter 15 - C++ As A "Better C"
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
C++ Templates.
Introduction to C++ Systems Programming.
Basic Elements of C++.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Basic Elements of C++ Chapter 2.
(5 - 1) Object-Oriented Programming (OOP) and C++
Programming Assignment #4 Binary Trees in C++
Introduction to C++ Programming
Pointers, Dynamic Data, and Reference Types
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Dr. Bhargavi Dept of CS CHRIST
Variables, Identifiers, Assignments, Input/Output
Classes and Objects.
Classes, Constructors, etc., in C++
Containers and the Standard Template Library (STL)
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Miscellaneous C++ Topics
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Introduction to C++ Programming
Scope Rules and Storage Types
Differences between Java and C
Your first C and C++ programs
(5 - 1) Object-Oriented Programming (OOP) and C++
CS150 Introduction to Computer Science 1
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
C++ Programming Lecture 3 C++ Basics – Part I
Programs written in C and C++ can run on many different computers
Chapter 15 - C++ As A "Better C"
Capitolo 1 – Introduction C++ Programming
A Deeper Look at Classes
4.1 Introduction Arrays A few types Structures of related data items
Introduction to Classes and Objects
Presentation transcript:

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, A-Term 2012 Introduction to C++

Reading Absolute C++, Chapter 1 Absolute C++, Chapter 6 Advice Tour of C++ Absolute C++, Chapter 6 Classes and structs Advice Don’t panic! All will become clear in time. You don’t need to know every detail of C++ to write good programs Focus on programming techniques, not language details CS-2303, A-Term 2012 Introduction to C++

What Is C++? A federation of (at least) four languages Note: Objective C was invented at about the same time, with similar goals. What Is C++? A federation of (at least) four languages C — with a few minor syntactic differences Files & I/O Use new and delete instead of malloc() and free() Inline Functions … Template C++ For defining and creating templates Object-oriented C++ Classes Inheritance and Multiple Inheritance Function and Operator Overloading References and Reference Parameters Default Arguments Standard Template Library Many tools Templates for containers CS-2303, A-Term 2012 Introduction to C++

Compiling C++ Use gcc, Eclipse, Visual Studio, etc. File types See Lab #1 File types .cc, .cp, .cpp, .CPP, .cxx, .c++, .C .h, .H In Linux gcc will recognize C++ file extensions and compile them but won’t get the libraries and defaults right g++ will set language to C++ and link to correct libraries by default Some of these have special properties. CS-2303, A-Term 2012 Introduction to C++

In this Topic A Simple C++ Example C++ Input/Output Similarities and differences between C and C++ Brief tour of Chapters 4 & 5 References and Reference Parameters Namespaces Including scope resolution operator "::" CS-2303, A-Term 2012 Introduction to C++

A Simple C++ Example // C++ simple example C++ style comments #include <iostream> //for C++ Input and Output int main () { int number3; std::cout << "Enter a number:"; std::cin >> number3; int number2, sum; std::cout << "Enter another number:"; std::cin >> number2; sum = number2 + number3; std::cout << "Sum is: " << sum <<std::endl; return 0; } C++ style comments standard output stream object stream insertion operator stream extraction operator standard input stream object stream manipulator Concatenating insertion operators CS-2303, A-Term 2012 Introduction to C++

Simple C++ Program (continued) <iostream> Must be included for any program that outputs data to the screen or inputs data from the keyboard using C++ style stream input/output. Replaces <stdio.h> of C C++ requires you to specify the return type, possibly void, for all functions. Specifying a parameter list with empty parentheses is equivalent to specifying a void parameter list in C. CS-2303, A-Term 2012 Introduction to C++

Notes on Simple C++ Program Stream manipulator std::endl Outputs a newline. Flushes the output buffer The notation std::cout specifies a name (cout) that belongs to the namespace std. Note: std::ends flushes the buffer but does not add newline. To be explained later CS-2303, A-Term 2012 Introduction to C++

Header Files C++ Standard Library header files Each contains a portion of the Standard Library. Function prototypes for the related functions Definitions of various class types and functions Constants needed by those functions “Instruct” the compiler on how to interface with library and user-written components. Use #include directive to include class or interface in a program. Note: You may encounter standard header file names ending in .h or .H These are “old-style” header files They are superseded by the C++ Standard Library header files CS-2303, A-Term 2012 Introduction to C++

C++ Standard Library header files <iostream> <iomanip> <fstream> <ifstream>, <ofstream> <string> <cstring> <cstdlib> <cmath> <complex>, <numeric> <ctime> <iterator> … <vector> <list> <queue> <stack> <deque> <map> <set> <bitset> CS-2303, A-Term 2012 Introduction to C++

Libraries for Next Assignment For PA4 <ifstream> stream input from file <ofstream> stream output to file <string> String management CS-2303, A-Term 2012 Introduction to C++

Keywords Shared with C CS-2303, A-Term 2012 Introduction to C++

New Keywords in C++ CS-2303, A-Term 2012 Introduction to C++

Types and Declarations Integer and floating point types Much like C bool Values true and false Use instead of C zero and non-zero char and wchar_t char: usually 8 bits, implementation dependent wchar_t: larger character sets – Unicode, international character sets, etc. Enumerations Like C Declarations, initializations, typedefs A lot like C Beware! C++ will convert between integers and bool without telling you! CS-2303, A-Term 2012 Introduction to C++

Ch. 5 – Pointers, Arrays, and Structs Pointers — like pointers in C May point to any type T or to void Unary '&' operator means “create a pointer” Unary ‘*' operator means “dereference a pointer” Simple arrays A lot like C May have any type T as elements Related to pointers as in C However, Use vector or valarray containers from Standard Template Library (STL) Recommend Advice:– Use 0 (i.e.,zero) instead of NULL CS-2303, A-Term 2012 Introduction to C++

Ch. 5 – Pointers, Arrays, and Structs (continued) In C, we introduced a struct as “like a Java class, but with no methods” In C++, a struct IS A class! The keyword struct can be used wherever the keyword class can be used An vice versa! The ONLY difference is that members of a struct are, by default, public class members are by default private public and private access specifiers may be included anywhere in a struct or a class CS-2303, A-Term 2012 Introduction to C++

structs and classes (continued) By definition:– struct s { … is shorthand for class s { public: … Stylistic advice:– Use struct when ALL members are public; otherwise, use class CS-2303, A-Term 2012 Introduction to C++

struct example Example:– Usage:– struct address{ char * name; long int number; char * street; char * town; char state[2]; long zip; }; //requires a semicolon after '}' Usage:– address jd; // don’t need to say “struct” as we did in C jd.name = “Jim Dandy”; jd.number = 61; CS-2303, A-Term 2012 Introduction to C++

Type Equivalence Two structs are different types, even when the have identical members §5.7.1 Example struct S1 { int a; }; struct S2 { int a; }; S2 = S1; // illegal! CS-2303, A-Term 2012 Introduction to C++

Questions? CS-2303, A-Term 2012 Introduction to C++

Memory Allocation from Heap new and delete for structs, classes, etc. Example class Table { …} … Table *p = new Table; //allocate and initialize Table *q = new Table; //new objects from Heap … delete p; // free objects, clean up, delete q; // return memory to Heap See §10.1, Absolute C++ CS-2303, A-Term 2012 Introduction to C++

Memory Allocation (continued) new and delete[] for arrays Example char * s = new char[length]; // allocate new arrays int * t = new int[count]; // from Heap … s[i] = 'x'; // use arrays as in C int x = t[j]; … delete[] s; // free whole arrays, return delete[] t; // memory to Heap See §10.2 It is usually incorrect to say delete s; delete t; CS-2303, A-Term 2012 Introduction to C++

Memory Allocation (concluded) Always use new and delete or delete[] Never, ever use malloc() and free() malloc() doesn’t correctly initialize objects Especially class objects! free() doesn’t correctly destroy objects delete doesn’t correctly destroy individual objects of arrays Must use delete[] CS-2303, A-Term 2012 Introduction to C++

Questions? CS-2303, A-Term 2012 Introduction to C++

BIG difference from Java References in C++ Definition Reference:– An Alternative Name for an object BIG difference from Java References are only created in declarations and parameters A reference can only appear where the object itself could have appeared See §8.3 in Absolute C++ CS-2303, A-Term 2012 Introduction to C++

Simple References void f() { int j = 1; int &r = j; //r and j refer to the exact same int int x = r; // x now is 1 r = 2; // j now is 2 } //f int k; int &r1 = k; // okay: r1 is initialized int &r2; // error; initializer missing extern int &r3; //okay; r3 defined elsewhere Sometimes, reference declarations are written as int& r1 = k; CS-2303, A-Term 2012 Introduction to C++

Simple References (continued) This '&' is the unary address operator brought over from C It is used here to create a reference! void g() { int ii = 0; int &rr = ii; rr++; // ii now is 1 int *pp = &rr; // pp now points to ii } //g Note: This declares a pointer exactly as in C, and initializes it with the address of rr (which is another name for ii) CS-2303, A-Term 2012 Introduction to C++

Example Usage of a Reference int grid[1000]; int rowSize, x, y; ... int &element = grid[x*rowSize+y]; ... /* computations on integer named element */ CS-2303, A-Term 2012 Introduction to C++

Reference Parameters An alias for its corresponding argument in a function call. & placed after the parameter type in the function prototype and function header Example int &count in a function header Pronounced as “count is a reference to an int” Parameter name in the called function body actually refers to the original variable in the calling function. CS-2303, A-Term 2012 Introduction to C++

Reference Parameter Example C version void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // void swap(…) C++ version void swap (int &a, int &b) { int temp = a; a = b; b = temp; Hazard: a NULL pointer Non-hazard: no pointer here CS-2303, A-Term 2012 Introduction to C++

Notes on References and Pointers Pointers in C do multiple duty Links, as in linked lists and trees Parameters, where the function needs to return a value to an argument provided by the caller Short-hand, a short way of referring to an object that otherwise would need a complex expression … C++ introduces references to address both of these cases CS-2303, A-Term 2012 Introduction to C++

Java vs. C++ References In Java, a reference is a data type. It can be assigned to, compared, copied, stored, etc. Same reference variable can refer to different objects at different times during execution In C++, a reference is an alias for an object It cannot be assigned to; assignment is through the reference to the underlying object Similar to dereferencing a pointer in C It cannot be compared; comparison applies to underlying object A reference always refers to the same object for the duration of its scope CS-2303, A-Term 2012 Introduction to C++

Repeat Three Times A C++ reference is not a pointer, … And neither of them resembles a Java reference CS-2303, A-Term 2012 Introduction to C++

Questions? CS-2303, A-Term 2012 Introduction to C++

Namespace A logical grouping of names … to set them apart from other names … to avoid conflicts among similar names See §8.2 CS-2303, A-Term 2012 Introduction to C++

Namespace Example From slide #7 // C++ simple example #include <iostream> //for C++ Input and Output int main () { int number3; std::cout << "Enter a number:"; std::cin >> number3; int number2, sum; std::cout << "Enter another number:"; std::cin >> number2; sum = number2 + number3; std::cout << "Sum is: " << sum <<std::endl; return 0; } From slide #7 CS-2303, A-Term 2012 Introduction to C++

Namespaces (continued) Names cout, cin, endl are declared in <iostream> … … but are not directly visible to program The are part of namespace std … which is visible! Need scope resolution operator '::‘ To get at things from a namespace CS-2303, A-Term 2012 Introduction to C++

Scope Resolution Operator std::cout The object cout that is declared in namespace std void BinaryTree::PrintTree The method PrintTree that is declared in class BinaryTree (needed when implementing PrintTree) CS-2303, A-Term 2012 Introduction to C++

“Using” Directive #include <iostream> using std::cout; using std::cin; using std::endl; … int main() { double sideValue; cout << "\nEnter the side " " length of your cube: "; cin >> sideValue; cout << "Volume of cube with “ "side " << sideValue << " is " << cube( sideValue ) << endl; return 0; } // int main() Adds cout, cin, endl from namespace std to current scope These names may now be used without qualification CS-2303, A-Term 2012 Introduction to C++

Common C++ Programming Error Forgetting to say “Using” You get undeclared identifiers Even though you include the appropriate header file! Using std Bad style Makes all names in namespace std visible … whether you need them or not! CS-2303, A-Term 2012 Introduction to C++

Questions? CS-2303, A-Term 2012 Introduction to C++