+ All Categories
Home > Documents > Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro ›...

Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro ›...

Date post: 25-Jun-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
72
Transcript
Page 1: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Overview

Presupposes knowledge of basic expression and statementsyntax.

Concentrates on C++ data and functions.

C++ Introduction

Page 2: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Obligatory Hello World

In hello.cc:

#include <iostream>

int main() {

std::cout << "hello world" << std::endl;}

C++ Introduction

Page 3: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

C++ contains Three Languages

1 A better C. C++ is largely a superset of C. Some of theimprovements made by C++ have worked their way back to C.

2 An object-oriented programming language. Supportsmultiple inheritance.

3 A generic programming language supporting code with typevariables. So the same code can support multiple types.

C++ Introduction

Page 4: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

C++ Integral Types

char, short, int, long and long long. Min bits 8, 16, 16,32, 64 respectively. Standard guarantees

1 == sizeof(char) <= sizeof(short) <= sizeof(int)<= sizeof(long) <= sizeof(long long)

Can be signed or unsigned. The default is signed exceptfor a plain char whose signed-ness is unde�ned.Do not use unsigned except for very low-level code.

C++ Introduction

Page 5: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

C++ Integer Types Continued

Integer literals can be speci�ed using character codes, decimal,octal, hexadecimal and binary literals.

int a = 42; //signedsigned b = 052; //octal, same as `int b = 42;`char c = '*'; //also 42 in ASCIIunsigned d = 0x2a; //also 42short e = 0b0010'1010; //also 42; ' ignored

long f = 42L; //long literal uses `l`, `L` su�xlong long g = 42LL; //long long literal uses ll, LL su�x

char and short are merely storage types; i.e. they usuallyoccupy less memory than int's. When used in expressionsthey always become int's.

C++ Introduction

Page 6: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

What does f() do?char f(char c) {

return('a' <= c && c <= 'z') ? 'A' + c - 'a' : c;

}

What assumption does it make?

Write a function digitCharToInt() which converts a charwhich is the code for a digit to the corresponding integer.Does it make any assumptions? Can you write it without thoseassumptions?

C++ Introduction

Page 7: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Solution to Exercise

f() converts a lowercase alphabetic character to uppercase. Itreturns all other characters unchanged.

It assumes that the codes for lowercase and uppercase lettersare contiguous and have the same sequence of letters. This istrue for common character codes like ASCII and UTF-8.Nevertheless, this kind of code is reminiscent of 1970s codeand should not be used; library functions should be usedinstead.

The following assumes that the character codes for digits arecontiguous and ordered by the values of the correspondingintegers.

int digitCharToInt(char digit) {

assert('0' <= digit && digit <= '9');

return digit - '0';

}

C++ Introduction

Page 8: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Some Other Primitive Types

Boolean type Type bool with literals true and false.

bool flag = true;

Floating point types float, double and long double. floatis a storage type which is usually IEEE-754-32;double is usually IEEE-754-64. Normal literalnotation.

const double avogadro = 6.0221409e+23;

�oat x = 1.0f; //f or F su�x for �oat literals.long double y = 2.3L; //l or L for

//long double literals

C++ Introduction

Page 9: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Memory

Memory is visible to C++ programmers.

Memory is usually organized as a sequence of 8-bit bytes.

32-bit computers allows up to 232 bytes of memory; 64-bitcomputers allows up to 264 bytes of memory.

Each byte has an address. 32-bit computers require 32 bitaddresses (8 hexets), 64-bit computers require 64-bit addresses(16 hexets).

[Computer architectures usually have a natural word size which isthe number of bits for which their instructions are optimized.Usually 4 bytes for 32-bit computers, 8 bytes for 64-bit computers.The size of a C++ int usually corresponds to this natural wordsize.]

C++ Introduction

Page 10: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Values and Variables

A value is an interpretation of some sequence of bits based ona type. For example, 0001_0110 when interpreted as aninteger has value 22.

A value is immutable.

A variable is a name given to some sequence of memorylocations.

int x = 22; //allocate sizeof(int) memory; name it x//initialize to value 22

Since memory can be changed, variables are mutable:x = 42; //change x memory to value 42

C++ Introduction

Page 11: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Pointers

A pointer is a value which holds a memory address.int i = 22;

int j = 44;

int* p = &i; //int* declares p as a pointer to `int`;//&i is address of i;//hence ip initialized to point to i

C++ Introduction

Page 12: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Pointers Continued

Assume continuation of example from previous slide:

Pointers can be explicitly dereferenced.int k = *p; //*p dereferences pointer p

//k initialized to 22*p = 42; //assignment statement sets i to 42.

Pointers can be changed.p = &j; //change p to point to j*p = 99; //changes j to 99

C++ Introduction

Page 13: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Pointers Continued

Pointers can be null. C++ uses special nullptr literal whichcan be used for any pointer type.

double* dp = nullptr;

int* ip = nullptr;

Avoids C confusion of NULL with 0.

C++ Introduction

Page 14: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

References

A reference is a value which holds a memory address.int i = 42;

int& r = i; //declares r as a reference to i.

Looks similar to pointers, but unlike a pointer, a reference isautomatically dereferenced whenever it is used. So areference is always an alias for the value it is pointing to.

C++ Introduction

Page 15: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

References Continued

Since a reference is always dereferenced, assigning to areference changes the pointed-to value, not the reference.

Since a reference cannot be changed, it can only be initialized.

So references are constant pointers which are alwaysdereferenced when used.

References cannot normally be null. But you can do:int* p = nullptr;

int& r = *p; //reference set to null

which Scott Meyers calls "evil, pure and simple". Might occurless directly.

C++ Introduction

Page 16: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Reference Examples

int i = 22;

int j = 44;

int& r = i; //r references ir = 42; //changes i to 42.j = r; //changes j to 42r = 99; //changes i to 99; j remains at 42

C++ Introduction

Page 17: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

Fill in the values of i and j after each statement:

int i = 022;

int j = 42;

int* p = &j;

int& r = i;

*p = 99;

j = r + 2;

r = j * 2;

C++ Introduction

Page 18: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Solution to Exercise

Code in ref-ptrs.cc with log.

int i = 022; //i: 18, j: undef; 022 is octal,int j = 42; //i: 18, j: 42int* p = &j; //i: 18, j: 42int& r = i; //i: 18, j: 42*p = 99; //i: 18, j: 99; *p aliases jj = r + 2; //i: 18, j: 20; r aliases ir = j * 2; //i: 40, j: 20; r aliases i

C++ Introduction

Page 19: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Aliasing

Both pointers and references allow aliasing:int i = 99;

int* p = &i; //*p aliases iint& r = i; //r aliases i

Aliasing makes code hard to understand; also makes it hard forcompilers to optimize.

Avoid if possible, but often necessary.

C++ Introduction

Page 20: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Declaration Syntax Pitfalls

The declaration int* p, q; declares p as a pointer to an int

but q simply as an int.

Similarly, the declaration int& r = q, s; declares r as areference to an int but s simply as an int.

The spacing around the * and & does not matter. Hence onecan write int* p, int *p or int * p; and.~int& r~, int &r orint & r.

I �nd int *p, q; int &r = q, s; less confusing, but C++programmers traditionally use the int* p, q; int& r = q,

s;.

Avoid problems by not declaring multiple variables using asingle declaration. Some style guides forbid doing so.

C++ Introduction

Page 21: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Declaring Immutable Variables

const implies that value cannot change after initialization.

const int a = 22;

int b = 33;

a = 44; //errorb = 55; //okconst int *p = &a; //pointer to const value*p = 44; //errorp = &b; //ok*p = 44; //still errorint *const q = &b; //const pointer*q = 44; //okq = &a; //errorconst int *const r = &b; //const pointer to const value*r = a; //errorr = &a; //error

C++ Introduction

Page 22: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Declaring Immutable Variables with Values Initialized atCompile-Time

constexpr implies const and that initial value can be evaluated atcompile time.

constexpr double avogadro = 6.0221409e+23;//okconstexpr �oat multiplier = 2.0f; //okconstexpr double avogadroMultiple =

multiplier*avogadro; //okconst int mult2 = 3; //okconstexpr avogadroMult = mult2*avogadro; //error

C++ Introduction

Page 23: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

Given that:

Loosing const-ness is an error.

Constant behavior carries over to references.

which of the following lines are in error?

const int a;const int& b = a;

int *p = &a;

const int *q = &a;

constexpr int c = b;

C++ Introduction

Page 24: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Solution to Exercise

Code in constness.cc with log.

const int a; //ERR: no initializerconst int& b = a; //OKint *p = &a; //ERR: ptr to non-const will

//allow changing a.const int *q = &a; //OKconstexpr int c = b; //ERR: b init at runtime, hence

//its value not known at compile-time//so not a compile-time constexpr

C++ Introduction

Page 25: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Arrays

An array refers to a block of memory containing multipleentities having the same type.

int a[10]; //a is an array of 10 int's

It is possible to omit the number of elements in a declaration ifit can be deduced from an initializer.

int a[] = { 1, 2, 3 }; //a is an array of 3 int's.

The size of an array cannot be changed once it has beeninitialized. (dynamic size alternative is std::vector).

A common idiom used to automatically calculate the numberof elements in an array is sizeof(a)/sizeof(a[0]). The latteris an example of a C++ constexpr expression only if thenumber of elements in a are known at compile time.

C++ Introduction

Page 26: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Arrays and Pointers

Every use of an array name is treated as a constant pointer to its�rst element except in two situations:

The array name is being declared.As an operand of sizeof().

int a[10]; //array of 10 `int`'sint s = sizeof(a); //40 if `int` is 4 bytesint *p = &a[2]; //pointer to 3rd element of a[]int *q = a + 1; //pointer to 2nd element of a[]int *r = 4 + a; //pointer to 5th element of a[]const int i = 2;

a[3] = 22; //assign 4th element of a[]*(a + i) = 33; //assign 3rd element of a[]*(q + i) = 44; //assign fourth element of a[]i[q] = 55; //assign fourth element of a[]a = &s; //compile-time error

C++ Introduction

Page 27: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

Show the variables which change after each step. Identify anyerrors.

const int a[] = { 1, 2, 3, };

a[4] = 99;

const int* p = a;

p[2] = 4;

const int* q = &a[1];

q[1] = 5;

int* s = &a[2];

*s = 6;

int& r = a[0];

int i = r;

C++ Introduction

Page 28: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Solution to Exercise

const int a[] = //a[] initialized{ 1, 2, 3, };

a[4] = 99; //ERR: violates constconst int* p = a; //p initializedp[2] = 4; //a[4], but violates constconst int* q = //q initiatized

&a[1];

q[1] = 5; //a[2], but violates constint* s = &a[2]; //ERR: violates const*s = 6; //a[2] if s decl was okint& r = a[0]; //ERR: violates constint i = r; //i init to 1 if r had been OK

C++ Introduction

Page 29: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Iterating Over an Array

Functions to sum an array using indexes and pointers respectively.Since array name degenerates into a pointer, we need to tracknumber of elements in array explicitly. In sum-array.cc:

intmain() {

int a[] = { 1, 2, 3, 4 };

constexpr size_t n = sizeof(a)/sizeof(a[0]);std::cout << sumArrayUsingIndexes(a, n) //10

<< ' '

<< sumArrayUsingPointers(a, n) //10<< std::endl;

}

C++ Introduction

Page 30: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Interating Over an Array Using Indexes

static intsumArrayUsingIndexes(const int a[], int n){

int sum = 0;

for (int i = 0; i < n; i++) {

sum += a[i];

}

return sum;

}

C++ Introduction

Page 31: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Interating Over an Array Using Pointers

static intsumArrayUsingPointers(const int* a, int n){

int sum = 0;

const int* beginP = a;

const int* endP = a + n; //one beyondfor (const int* p = beginP; p < endP; p++) {

sum += *p;

}

return sum;

}

C++ Introduction

Page 32: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Iterating Over an Array: Retrospective

When using indexes, we speci�ed range for index i as ahalf-open interval [0, n) with 0 <= i < n.

When using pointers, we speci�ed range for pointer p as ahalf-open interval [beginP, endP) with beginP <= p <

endP.

Iterating over array using pointers will be generalized intoiterators supported by the standard template library.

C++ Introduction

Page 33: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Parameter Passing: Call-By-Value

Call-by-value means that copies of actual parameters are passed toa function.

int f(int a, int b) { a *= 2; return a + b; }

int a = 22;

int x = f(a, 3); //x set to 47//a is still 22 since a *= 2 only changed copy of a

C++ Introduction

Page 34: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Writing a swap() Using Call-By-Value

Impossible to write a swap() using call-by-value:

void swap(int a, int b) {

int t = a;

a = b; b = t;

}

int a = 2;

int b = 3;

swap(a, b); //only copies are swapped//a, b unchanged with values 2 and 3

C++ Introduction

Page 35: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Writing a swap() Using Pointers

C only supports call-by-value. Hence the only way of writing aswap() in C is by passing pointers to the values to be swapped:

void swap(int *a, int *b) {

int t = *a;

*a = *b; *b = t;

}

int a = 2;

int b = 3;

swap(&a, &b); //passing pointers to a and b//swapped with a == 3 and b == 2

C++ Introduction

Page 36: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Parameter Passing: Call-By-Reference

C++ also allows call-by-reference where references to actualparameters are passed to a function.

int f(int& a, int& b) { a *= 2; return a + b; }

int a = 22;

int x = f(a, 3); //x set to 47//a changed to 44

Use call-by-reference when:

It is necessary to change actual parameter in caller.

For e�ciency, to avoid the copy overhead in call-by-value whenthe size of the parameter is large.

If possible, declare reference parameter const and obtainsafety.

C++ Introduction

Page 37: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Writing a swap() Using Call-By-Reference

Writing a swap() using call-by-reference:

void swap(int& a, int& b) {

int t = a;

a = b; b = t;

}

int a = 2;

int b = 3;

swap(a, b); //swaps the actual parameters//swapped with a = 3, b = 2

C++ Introduction

Page 38: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

What will be the value of i, j, x and y after executing thefollowing code?

int f(int* a, int& b) {

*a += 2;

b += *a;

return *a + b;

}

int i = 2;

int j = 3;

int x = f(&i, j);

int y = f(&x, x);

C++ Introduction

Page 39: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

Code in call-params.cc with log.

int f(int* a, int& b) {

//@1: *a aliases i: 2, b aliases j: 3//@2: *a aliases x: 11, b aliases x: 11*a += 2; //@1: *a and i: 4

//@2: *a, x, b: 13b += *a; //@1: b and j: 7

//@2: a, x, b: 26return *a + b;//@1: returns 11

//@2: returns 52}

int i = 2, j = 3;

int x = f(&i, j); //call @1//i: 4, j: 7, x: 11int y = f(&x, x); //call @2//i: 4, j: 7, x: 26, y: 52

C++ Introduction

Page 40: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Call-By-Reference Pitfalls

Exercise illustrated aliasing pitfalls of call-by-reference whereformals *a and b both aliased x in call f(&x, x).

With call-by-value it is possible to look at a call site anddetermine which arguments may be changed by the function.

Speci�cally, if there is an & in front of a variable being passedas a parameter, then that variable may be changed by thefunction.If there is no & in front of a variable being passed as aparameter, then that variable cannot be changed by thefunction (barring tricky macro craziness).

With call-by-reference, it is necessary to look at the functionde�nition to determine which variables in the caller may bechanged by the function.

If using call-by-reference for an argument which is not beingchanged, declare it as const to make it easy to determine it isnot being changed.

C++ Introduction

Page 41: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Function Overloading

C++ allows multiple functions with the same name within thesame scope as long as they can be distinguished by thenumber and types of their parameters.

Can get very tricky in the presence of automatic conversions.Best not to depend on these rules and make the overloadingvery clear.

int f(int i) { return i + 42; }

int f(int* p) { return *p + 4; }

int f(int a, int b) { return a - b; }

...

int x = f(3); //calls �rst f(); returns 45int y = f(&x); //calls second f(); returns 49int z = f(y, x); //calls third f(); return 4.

C++ Introduction

Page 42: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

User De�ned Types: Classes and Structs

A C++ class or struct is a type which aggregatesnon-homogeneous data.

An instance of a class or struct is created by calling aconstructor function which has the same name as the name ofthe type.

An instance of a class or struct can contain data members.The value of the data is speci�c to the instance.

Multiple instances of a class or struct share memberfunctions.

The default visibility of all struct members is public.

The default visibility of all class members is private.

Can overload operator ⊕ by de�ning function operator⊕().

C++ Introduction

Page 43: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

An Example struct

In struct-point.cc:

struct Point { //default visibility publicdouble x, y;

Point(double x, double y) //constructor: x(x), y(y) //member initializer list

{ } //empty constructor bodydouble distance(Point p) { //inlinedouble xDiff = p.x - x;

double yDiff = p.y - y;

return sqrt(xDiff*xDiff + yDiff*yDiff);

}

}; //semicolon absolutely necessary here

C++ Introduction

Page 44: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

An Example struct Continued

std::ostream& //overload << operatoroperator<<(std::ostream& strm, const Point& pt) {

return strm << "(" << pt.x << ", "

<< pt.y << ")";

}

int main() {

Point p1(1.0, 1.0); //call constr to initPoint p2(4.0, 5.0);

std::cout << p1.x - p2.x << std::endl; //-3std::cout << p1 << std::endl; //(1, 1)std::cout << p2 << std::endl; //(4, 5)std::cout << p1.distance(p2) << std::endl; //5

}

C++ Introduction

Page 45: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

An Example class

In class-point.cc:

class Point { //default visibility privatedouble x, y;

friend std::ostream&operator<<(std::ostream& strm, const Point& pt);

public:Point(double x, double y) : x(x), y(y) { }

double distance(Point p) { //inlinedouble xDiff = p.x - x;

double yDiff = p.y - y;

return sqrt(xDiff*xDiff + yDiff*yDiff);

}

}; //semicolon absolutely necessary here

C++ Introduction

Page 46: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

An Example class Continued

std::ostream& //overload << operatoroperator<<(std::ostream& strm, const Point& pt) {

return strm << "(" << pt.x << ", "

<< pt.y << ")";

}

int main() {

Point p1(1.0, 1.0);

Point p2(4.0, 5.0);

//compile error because x, y private//std::cout << p1.x - p2.x << std::endl;std::cout << p1 << std::endl; //(1, 1)std::cout << p2 << std::endl; //(4, 5)std::cout << p1.distance(p2) << std::endl; //5

}

C++ Introduction

Page 47: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Allocation Lifetimes

Each variable in a program has a lifetime de�ned as the time fromwhich the variable can be accesed till the time it can no longer beaccessed.

Program lifetime The variable is accessible the entire time theprogram is running. In C++, top-level variables andvariables speci�cally declared using the static orextern "storage class" have lifetime equal to that ofthe program. Uses static allocation.

Block lifetime The variable has a lifetime only from the point atwhich its declaration is encountered till the end of thecontaining block. Uses stack allocation.

Indeterminate lifetime A "variable" (which may have a di�erentlifetime) points to an unnamed block of memory. Thememory is explicitly allocated at the start of itslifetime and deallocated (explicitly in C++, implicitlyin garbage-collected languages) at the end of itslifetime This is done in C++ using new and delete.

C++ Introduction

Page 48: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Alloc-Dealloc

In alloc-delloc.cc:

class C {

const char *str;public:C(const char *str) : str(str) {

std::cout << "allocated C(" << str << ")"

<< std::endl;}

∼C() {

std::cout << "deallocated C(" << str << ")"

<< std::endl;}

};

C++ Introduction

Page 49: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Alloc-Dealloc main()

C c("static");int main() {

C c("stack");C *p = new C("dynamic");delete p;

}

C++ Introduction

Page 50: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Alloc-Dealloc Log

$ ./code/alloc-dealloc

allocated C(static)

allocated C(stack)

allocated C(dynamic)

deallocated C(dynamic)

deallocated C(stack)

deallocated C(static)

C++ Introduction

Page 51: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions 1

In autogen-fns1.cc:

struct A { std::string str; };

int main() {

A a1; //default constructorstd::cout << "init: a1.str: " << a1.str

<< "length: " << a1.str.length() << std::endl;a1.str = "hello";

A a2(a1); //copy constructorstd::cout << "1: a1.str: " << a1.str

<< " a2.str: " << a2.str << std::endl;a2.str = "goodbye";

a1 = a2; //assignment operatorstd::cout << "2: a1.str: " << a1.str

<< " a2.str: " << a2.str << std::endl;//default destructors for a2, a1 called

} C++ Introduction

Page 52: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions 1: Log

init: a1.str: length: 0

1: a1.str: hello a2.str: hello

2: a1.str: goodbye a2.str: goodbye

C++ Introduction

Page 53: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions

Default Constructor C() Generated only if no other constructor.

Copy Constructor C(const C&c) Generated when needed. Oftenneeded.

Assignment Operator C& operator=(const C& c) Generatedwhen needed. Often needed.

Destructor ~C()

Autogeneration can be avoided if functions de�ned explicitly.

C++ Introduction

Page 54: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions 2

In autogen-fns2.cc:

struct B {

std::string str;

B(std::string s) : str(s) {

std::cout << *this << " constr" << std::endl;}

B(const B& b) : str(b.str) {

std::cout << *this << " copy constr"

<< std::endl;}

B& operator=(const B& c) {

std::cout << *this << " = " << c << std::endl;str = c.str;

return *this;}

C++ Introduction

Page 55: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions 2 Continued

∼B() {

std::cout << *this << " destr" << std::endl;}

};

std::ostream&operator<<(std::ostream& strm, const B& b) {

return strm << "B(" << b.str << "): " << &b;

}

int main() {

//0-ary constr B b0; will cause errorB b1(std::string("hello")); //constrB b2(b1); //copy constrB b3("bye"); //constrb1 = b3; //assign operator//destructors called for b3, b2, b1

} C++ Introduction

Page 56: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Automatically Generated Functions 2: Log

B(hello): 0x7ffde7f0b9d0 constr #b1B(hello): 0x7ffde7f0b9f0 copy constr #b2B(bye): 0x7ffde7f0ba10 constr #b3#assigning b3 to b1B(hello): 0x7ffde7f0b9d0 = B(bye): 0x7ffde7f0ba10

B(bye): 0x7ffde7f0ba10 destr #b3B(hello): 0x7ffde7f0b9f0 destr #b2B(bye): 0x7ffde7f0b9d0 destr #b1

C++ Introduction

Page 57: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Exercise

Given a declaration and some statements, for each statementindicate whether it is in error and which member functions will berun by that statement.

struct C {

int val;C(int i) : val(i) { } //1C(C c) : val(c.val) { } //2C& operator=(C& c) { val = c.val; } //3

};

C c1;

C c2(22);C c3(c2);C c4 = C(33);C c5 = c2;

c2 = c4;

C++ Introduction

Page 58: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Solution to Exercise

Code in autogen-fns.cc with log.

struct C {

int val;C(int i) : val(i) { } //1C(C c) : val(c.val) { } //2C& operator=(C& c) { val = c.val; } //3

};

C c1; //ERR: no auto-gen default constrC c2(22); //int constr 1C c3(c2); //copy constr 2C c4 = C(33); //int constr 1C c5 = c2; //copy constr 2c2 = c4; //assign operator 3//note destructors for c5, c4, c3, c2 will run//at end of scope

C++ Introduction

Page 59: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Rule of Three

Whenever any of a copy constructor, assignment operator ordestructor are de�ned, all the rest must also be de�ned.Rule of thumb aka Law of The Big Three or The Big Three.

C++ Introduction

Page 60: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Class Which Encapsulates Pointer

ptr.cc shows problems with classes which encapsulate pointers(crude example, violates rule of three):

class Ptr {

int* ptr;

public:Ptr() : ptr(new int(42)) {

trace("create");}

Ptr(const Ptr& p) : ptr(p.ptr) {

trace("copy", &p);

}

C++ Introduction

Page 61: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Class Which Encapsulates Pointer Continued

∼Ptr() {

trace("DELETING!!");delete ptr;

}

private:void trace(std::string msg, const void* p=nullptr) {

std::cout << this << " (" << ptr << ") "

<< msg;

if (p) std::cout << " " << p;

std::cout << std::endl;}

};

C++ Introduction

Page 62: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Class Which Encapsulates Pointer Continued

static Ptr f(Ptr p) { return p; }

static Ptr g(Ptr& p) { return p; }

int main() {

Ptr p1;

Ptr p2 = f(p1);Ptr p3 = g(p1);

}

C++ Introduction

Page 63: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Class Which Encapsulates Pointer Annotated Log

0x7fff9afa_0780 (0x5600485a0e90) create

#copy for parameter p to f()0x7fff9afa_0790 (0x5600485a0e90) copy 0x7fff9afa0780

#looks like copy elision avoids copy for return value#copy constructor for p2 using copy0x7fff9afa_0788 (0x5600485a0e90) copy 0x7fff9afa0790

#remove temporary copy0x7fff9afa_0790 (0x5600485a0e90) DELETING!!

#g() does not make any copies; copy constr for p30x7fff9afa_0790 (0x5600485a0e90) copy 0x7fff9afa0780

#main() ends: delete p3, p2, p10x7fff9afa_0790 (0x5600485a0e90) DELETING!!

0x7fff9afa_0788 (0x5600485a0e90) DELETING!!

0x7fff9afa_0780 (0x5600485a0e90) DELETING!!

Deleted 0x5600485a0e90 multiple times!! Unacceptable.C++ Introduction

Page 64: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers

Build smart pointer which tracks number of references. Deletememory only when reference count goes to 0. Essential ideaillustrated by smart-ptr.cc:

template <typename T>class SmartPtr {

T *ptr;

std::size_t *refCount;

public:SmartPtr(T *p)

: ptr(p), refCount(new std::size_t(1)){

trace("create");}

C++ Introduction

Page 65: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers Continued

SmartPtr(const SmartPtr& p) :

ptr(p.ptr), refCount(p.refCount){

*refCount += 1; //sharing refCounttrace("copy", &p);

}

C++ Introduction

Page 66: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers Continued

∼SmartPtr() {

*refCount -= 1;

trace("delete");if (*refCount == 0) {

trace("DELETING!!!");delete ptr;

delete refCount;

}

}

T& operator*() { return *ptr; }

C++ Introduction

Page 67: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers Continued

private:void trace(std::string msg, const void *p=nullptr) {

std::cout << this << " (" << ptr << ", "

<< *refCount << ") " << msg;

if (p) std::cout << " " << p;

std::cout << std::endl;}

};

C++ Introduction

Page 68: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers Continued

static SmartPtr<int> f(SmartPtr<int> p) { return p; }

template<typename T>static SmartPtr<T> g(SmartPtr<T>& p) { return p; }

int main() {

int *p = new int(42);SmartPtr<int> p1(p);std::cout << "*p1 = " << *p1 << std::endl;SmartPtr<int> p2 = f(p1);*p2 = 33;

SmartPtr<int> p3 = g(p1);std::cout << "*p1 = " << *p1 << std::endl;std::cout << "*p2 = " << *p2 << std::endl;std::cout << "*p3 = " << *p3 << std::endl;

}

C++ Introduction

Page 69: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers Log

0x7ffdd09c2560 (0x563148d62e70, 1) create

*p1 = 42

0x7ffdd09c2580 (0x563148d62e70, 2) copy 0x7ffdd09c2560

0x7ffdd09c2570 (0x563148d62e70, 3) copy 0x7ffdd09c2580

0x7ffdd09c2580 (0x563148d62e70, 2) delete

0x7ffdd09c2580 (0x563148d62e70, 3) copy 0x7ffdd09c2560

*p1 = 33

*p2 = 33

*p3 = 33

0x7ffdd09c2580 (0x563148d62e70, 2) delete

0x7ffdd09c2570 (0x563148d62e70, 1) delete

0x7ffdd09c2560 (0x563148d62e70, 0) delete

0x7ffdd09c2560 (0x563148d62e70, 0) DELETING!!!

C++ Introduction

Page 70: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Smart Pointers in Standard Library

std:unique_ptr<T> Holds only pointer to object, so object isdeleted automatically when smart pointer goes out ofscope. Cannot be copied. The holder of the pointerowns the underlying object. Usually, size is same asthat of a raw pointer.

std:shared_ptr<T> Reference counting smart pointer. Can becopied. Object deleted only when last copy of smartpointer goes out of scope. Size is always twice that ofa raw pointer (it contains two pointers).Cycles of shared pointer objects will never be deletedbecause ref counts will never go to 0!

std:weak_ptr<T> Can be dangling pointers, hence nodereference operation. Can create a shared pointerfrom a weak pointer, returning null or throwing anexception if the weak pointer is dangling.Can be used to break cycles of shared pointers orimplementing object caches.

C++ Introduction

Page 71: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Memory Management in Modern C++

When building a class, use smart pointers to avoid burdeningclient with memory management issues.

Set up factory functions to return a std::unique_ptr<T>.Let client decide whether ownership should remain unique orshared (in which case it constructs a shared pointer from theunique pointer).

Use std::make_unique<T>() and std::make_shared<T>()

to avoid raw uses of new.

Use Resource Acquisition Is Initialization RAII technique wherethe memory used by an object is bound to the lifetime of thatobject.

C++ Introduction

Page 72: Presupposes knowledge of basic expression and statement ... › cs240 › slides › c++-intro › c++-intro.pdf · C++ contains Three Languages 1 A better C . C++ is largely a superset

Major Omissions

Besides basics, this presentation concentrated on providing aglimpse at memory management in modern C++. Topics omittedinclude:

Inheritance, virtual functions.

Standard template library.

Move semantics.

Templates.

Some of the above will be covered in the labs or in class whenneeded for the main subject matter of the course.

C++ Introduction


Recommended