Download presentation
Presentation is loading. Please wait.
Published bySarah Gray Modified over 6 years ago
1
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++
2
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++
3
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++
4
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++
5
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++
6
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++
7
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++
8
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++
9
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++
10
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++
11
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++
12
Keywords Shared with C CS-2303, A-Term 2012 Introduction to C++
13
New Keywords in C++ CS-2303, A-Term 2012 Introduction to C++
14
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++
15
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++
16
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++
17
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++
18
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++
19
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++
20
Questions? CS-2303, A-Term 2012 Introduction to C++
21
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++
22
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++
23
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++
24
Questions? CS-2303, A-Term 2012 Introduction to C++
25
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++
26
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++
27
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++
28
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++
29
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++
30
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++
31
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++
32
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++
33
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++
34
Questions? CS-2303, A-Term 2012 Introduction to C++
35
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++
36
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++
37
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++
38
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++
39
“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++
40
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++
41
Questions? CS-2303, A-Term 2012 Introduction to C++
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.