Post on 21-May-2020
Carnegie Mellon Worcester Polytechnic Institute
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)
Introduction to C++ CS-2303, A-Term 2012 1
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Reading
Absolute C++, Chapter 1 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
Introduction to C++ CS-2303, A-Term 2012 2
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
What Is C++?
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
Introduction to C++ CS-2303, A-Term 2012 3
Note: Objective C was invented at about the same time, with similar goals.
A federation of (at least) four languages
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Compiling C++
Use gcc, Eclipse, Visual Studio, etc. 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
Introduction to C++ CS-2303, A-Term 2012 4
Some of these have special properties.
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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 "::"
Introduction to C++ CS-2303, A-Term 2012 5
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
A Simple C++ Example
Introduction to C++ CS-2303, A-Term 2012 6
// 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; }
stream extraction operator standard input stream object
C++ style comments
stream manipulator Concatenating insertion operators
standard output stream object stream insertion operator
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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.
Introduction to C++ CS-2303, A-Term 2012 7
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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.
Introduction to C++ CS-2303, A-Term 2012 8
Note: std::ends flushes the buffer but does not add newline.
To be explained later
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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.
Introduction to C++ CS-2303, A-Term 2012 9
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
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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>
Introduction to C++ CS-2303, A-Term 2012 10
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Libraries for Next Assignment For PA4 <ifstream>
stream input from file <ofstream>
stream output to file <string>
String management
Introduction to C++ CS-2303, A-Term 2012 11
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Keywords Shared with C
Introduction to C++ CS-2303, A-Term 2012 12
C++ keywords
Keywords common to the C and C++ programming languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
New Keywords in C++
Introduction to C++ CS-2303, A-Term 2012 13
C++ keywords
C++-only keywords
and and_eq asm bitand bitor
bool catch class compl const_cast
delete dynamic_cast explicit export false
friend inline mutable namespace new
not not_eq operator or or_eq
private protected public reinterpret_cast static_cast
template this throw true try
typeid typename using virtual wchar_t
xor xor_eq
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 14
Beware! C++ will convert between integers and bool without telling you!
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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)
Introduction to C++ CS-2303, A-Term 2012 15
Recommend Advice:– Use 0 (i.e.,zero) instead of NULL
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 16
public and private access specifiers may be included anywhere in a struct or a class
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 17
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
struct example
Example:– 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;
Introduction to C++ CS-2303, A-Term 2012 18
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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!
Introduction to C++ CS-2303, A-Term 2012 19
Carnegie Mellon Worcester Polytechnic Institute
Questions?
Introduction to C++ CS-2303, A-Term 2012 20
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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++
Introduction to C++ CS-2303, A-Term 2012 21
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 22
It is usually incorrect to say delete s; delete t;
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Especially class objects! delete doesn’t correctly destroy individual objects of
arrays Must use delete[]
Introduction to C++ CS-2303, A-Term 2012 23
Carnegie Mellon Worcester Polytechnic Institute
Questions?
Introduction to C++ CS-2303, A-Term 2012 24
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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++
Introduction to C++ CS-2303, A-Term 2012 25
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 26
Sometimes, reference declarations are written as int& r1 = k;
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Simple References (continued)
void g() { int ii = 0; int &rr = ii; rr++; // ii now is 1 int *pp = &rr; // pp now points to ii
} //g
Introduction to C++ CS-2303, A-Term 2012 27
Note: This declares a pointer exactly as in C, and initializes it with the address of rr (which is another name for ii)
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Example Usage of a Reference int grid[1000];
int rowSize, x, y; ... int &element = grid[x*rowSize+y];
... /* computations on integer named element */
Introduction to C++ CS-2303, A-Term 2012 28
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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.
Introduction to C++ CS-2303, A-Term 2012 29
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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;
} // void swap(…)
Introduction to C++ CS-2303, A-Term 2012 30
Hazard: a NULL pointer
Non-hazard: no pointer here
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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 …
Introduction to C++ CS-2303, A-Term 2012 31
C++ introduces references to address both of these cases
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 32
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Repeat Three Times
A C++ reference is not a pointer, … A C++ reference is not a pointer, … A C++ reference is not a pointer, … And neither of them resembles a
Java reference
Introduction to C++ CS-2303, A-Term 2012 33
Carnegie Mellon Worcester Polytechnic Institute
Questions?
Introduction to C++ CS-2303, A-Term 2012 34
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Namespace A logical grouping of names
… to set them apart from other names
… to avoid conflicts among similar names
See §8.2
Introduction to C++ CS-2303, A-Term 2012 35
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
Namespace Example
Introduction to C++ CS-2303, A-Term 2012 36
// 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
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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
Introduction to C++ CS-2303, A-Term 2012 37
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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)
Introduction to C++ CS-2303, A-Term 2012 38
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
“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()
Introduction to C++ CS-2303, A-Term 2012 39
Adds cout, cin, endl from namespace std to current scope
These names may now be used without qualification
Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute
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!
Introduction to C++ CS-2303, A-Term 2012 40
Carnegie Mellon Worcester Polytechnic Institute
Questions?
Introduction to C++ CS-2303, A-Term 2012 41