102
C++ Review September 28, 2016 CMPE 250 C++ Review September 28, 2016 1 / 102

C++ Review - CmpE WEB

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C++ Review - CmpE WEB

C++ Review

September 28, 2016

CMPE 250 C++ Review September 28, 2016 1 / 102

Page 2: C++ Review - CmpE WEB

Contents

History and overview

Basic features

Parameter passing

Classes

Inheritance and virtual

Header file

IO

Memory Management

Big three: destructor, copy constructor, and assignment operator

Const

Template

CMPE 250 C++ Review September 28, 2016 2 / 102

Page 3: C++ Review - CmpE WEB

History of C++

1972: C language developed at Bell Labs

Dennis Ritchie wrote C for Unix OSNeeded C for work with Unix

late 70s: C becomes popular for OS development by many vendorsMany variants of the language developedANSI standard C in 1987-89

CMPE 250 C++ Review September 28, 2016 3 / 102

Page 4: C++ Review - CmpE WEB

History of C++ (continued)

early 80s: Bjarne Stroustrup adds OO features to C creating C++

90s: continued evolution of the language and its applications

preferred language for OS and low level programmingpopular language for application developmentlow level control and high level power

In mid-2011, the new C++ standard (called C++11) was finished.

CMPE 250 C++ Review September 28, 2016 4 / 102

Page 5: C++ Review - CmpE WEB

Conceptually what is C++ ?

Alternatives:

is it C, with many more options and features?is it an OO programming language with C as its core?is it a development environment?

On most systems it is a development environment, language, andlibrary, used for both procedural and object oriented programming,that can be customized and extended as desired

CMPE 250 C++ Review September 28, 2016 5 / 102

Page 6: C++ Review - CmpE WEB

Versions of C++

ANSI C++

Microsoft C++

GNU C++ (GCC)

Many older versions (almost annual) including different version of C,too

Many vendor specific versions

Many platform specific versions

CMPE 250 C++ Review September 28, 2016 6 / 102

Page 7: C++ Review - CmpE WEB

Characteristics of C++ as a Computer Language

Procedural

Object Oriented

Extensible

...

CMPE 250 C++ Review September 28, 2016 7 / 102

Page 8: C++ Review - CmpE WEB

Other OO Languages

Smalltalk

pure OO language developed at PARC

Java

built on C/C++objects and data types

Eiffel and others

CMPE 250 C++ Review September 28, 2016 8 / 102

Page 9: C++ Review - CmpE WEB

What you can do with C++

Apps (standalone, Web apps, components)

Active desktop (Dynamic HTML, incl. Web)

Create graphical apps

Data access (e-mail, files, ODBC)

Integrate components w/ other languages

Program intelligent robots

CMPE 250 C++ Review September 28, 2016 9 / 102

Page 10: C++ Review - CmpE WEB

Disadvantages of C++

Tends to be one of the less portable languages

Complicated?

many operators, intricate precedence, pointers, etc.can control everythingmany exceptions and special casestremendous libraries both standard, vendor specific, and available forpurchase, but all are intricate

Aspects above can result in high maintenance costs

CMPE 250 C++ Review September 28, 2016 10 / 102

Page 11: C++ Review - CmpE WEB

Advantages of C++

Available on most machines

Can get good performance

Can get small size

Can manage memory effectively

Can control everything

Good supply of programmers

Suitable for almost any type of program (from systems programs toapplications)

CMPE 250 C++ Review September 28, 2016 11 / 102

Page 12: C++ Review - CmpE WEB

Basic Features of C++

CMPE 250 C++ Review September 28, 2016 12 / 102

Page 13: C++ Review - CmpE WEB

Primitive Types

bool true or false (only C++)

char 8/16-bit

short 16-bit signed integer

int 32-bit signed integer

unsigned 32-bit unsigned integer

long 32 / 64-bit signed integer

float 32-bit floating point

double 64-bit floating point

CMPE 250 C++ Review September 28, 2016 13 / 102

Page 14: C++ Review - CmpE WEB

Operators and Precedence

[] . to access arrays elements / to access objectmethods and fields

expr++ expr- ++expr -

expr !

new (type)expr

* / %

+ - « » (integers only)

>= <=

== !=

&

CMPE 250 C++ Review September 28, 2016 14 / 102

Page 15: C++ Review - CmpE WEB

Operators and Precedence

ˆ

|&& (booleans only)

|| (booleans only)

?:

= += -= *= ....

C++ allows operator overloading

CMPE 250 C++ Review September 28, 2016 15 / 102

Page 16: C++ Review - CmpE WEB

Precedence Example

What is: 5 + 21 / 4 % 3= 5 + (21 / 4) % 3

= 5 + ( 5 % 3)

= 5 + 2

= 7

CMPE 250 C++ Review September 28, 2016 16 / 102

Page 17: C++ Review - CmpE WEB

Explicit Casting

(type) expression

Possible among all integer and float types

Possible among some class references

e.g. int i = (int) ( (double)5 / (double)3 )

CMPE 250 C++ Review September 28, 2016 17 / 102

Page 18: C++ Review - CmpE WEB

Implicit Casting

Applied automatically provided there is no loss of precision

float =⇒ doubleint =⇒ double

Exampleint iresult, i=3;

double dresult, d=3.2;

dresult = i/d =⇒ implicit castingdresult=0.9375

iresult = i/d =⇒ error! Why? Loss inprecision, needs explicit casting

CMPE 250 C++ Review September 28, 2016 18 / 102

Page 19: C++ Review - CmpE WEB

Control Flow

if (boolean)statement;

else if(boolean)statement2;

elsestatement3;

Booleans only, not integers!if (i > 0) =⇒ correct

if (i = 2) =⇒ correct / incorrect ?

CMPE 250 C++ Review September 28, 2016 19 / 102

Page 20: C++ Review - CmpE WEB

Switch / case

switch (controlVar){

case ’a’ :statement-1break;

case ’b’ :statement-2break;

default :statement-3break;

}

Do not forget the break command to avoid a surprise result!

CMPE 250 C++ Review September 28, 2016 20 / 102

Page 21: C++ Review - CmpE WEB

Loops

while(<boolean>)statement;

dostatement;

while(<boolean>)

for(init-expr; <boolean>; incr-expr)statement;

CMPE 250 C++ Review September 28, 2016 21 / 102

Page 22: C++ Review - CmpE WEB

Loop Refresher

Which loops must execute their statements at least once?

Which loops can choose to never execute their statements?

Which value of the boolean indicates to do the statements again?

CMPE 250 C++ Review September 28, 2016 22 / 102

Page 23: C++ Review - CmpE WEB

Some Conventions for Variable Names

Use letters and numbers

Do not use special characters including spaces, dots, underlines,pound signs, etc.

The first letter will be lower case

Use variable names that are meaningful (except for occasionalcounters that we might call i, j, x, etc.)

You can concatenate words, and capitalize each after the first, e.g.,bankBal, thisAcctNum, totAmt

If you abbreviate, be consistent. For example do not use bothbankBal and totalBalance as variable names.

CMPE 250 C++ Review September 28, 2016 23 / 102

Page 24: C++ Review - CmpE WEB

Some Conventions for Struct and Class Names

In creating names of structs and classes, apply the same rules as forvariable names, except the first character will be upper case

Example:

an object’s name: myCarthe struct or class name: Car

Another Example: aPerson and Person

CMPE 250 C++ Review September 28, 2016 24 / 102

Page 25: C++ Review - CmpE WEB

Parameter passing

CMPE 250 C++ Review September 28, 2016 25 / 102

Page 26: C++ Review - CmpE WEB

Passing Parameters

C++ allows for three different ways of passing parameters:

Pass “by value”

e.g. foo (int n)Appropriate for small objects (usually primitive types) that should not bealtered by the function call

Pass “by constant reference”

e.g. foo(const T& myT)Appropriate for large objects that should not be altered by the function call

Pass “by reference”e.g. foo(bool & errFlag)Appropriate for small objects that can be altered by the function call Arraytypes are always passed “by reference”

CMPE 250 C++ Review September 28, 2016 26 / 102

Page 27: C++ Review - CmpE WEB

Passing by value

void square(int i){

i = i*i;}int main(){

int i = 5;square(i);cout << i << endl;return 0;

}

CMPE 250 C++ Review September 28, 2016 27 / 102

Page 28: C++ Review - CmpE WEB

Passing by reference

void square(int& i){

i = i*i;}int main(){

int i = 5;square(i);cout << i << endl;return 0;

}

CMPE 250 C++ Review September 28, 2016 28 / 102

Page 29: C++ Review - CmpE WEB

Passing by constant reference

void square(const int& i){

i = i*i;}int main(){

int i = 5;square(i);cout << i << endl;return 0;

}

Will this work?

CMPE 250 C++ Review September 28, 2016 29 / 102

Page 30: C++ Review - CmpE WEB

What is a reference?

An alias – another name for an object.

int x = 5;int &y = x; // y is a

// reference to xy = 10;

What happened to x?What happened to y? – y is x.

CMPE 250 C++ Review September 28, 2016 30 / 102

Page 31: C++ Review - CmpE WEB

Why are they useful?

When passing argument of large size (class type), can save space

Sometimes need to change a value of an argument

Can be used to return more than one value (pass multiple parametersby reference)

CMPE 250 C++ Review September 28, 2016 31 / 102

Page 32: C++ Review - CmpE WEB

How are references different from Pointers?

Reference

int a = 10;int b = 20;int &c = a;c = b;

What is the value of a?

Pointer

int a = 10;int b = 20;int *c = &a;c = &b;

CMPE 250 C++ Review September 28, 2016 32 / 102

Page 33: C++ Review - CmpE WEB

Classes

CMPE 250 C++ Review September 28, 2016 33 / 102

Page 34: C++ Review - CmpE WEB

Classes

Provide a mechanism for defining classes of objects.

We can define the class of all computers to have certain characteristics.An instance of a computer is your home PC.

Classes contain member variables and member functions.

CMPE 250 C++ Review September 28, 2016 34 / 102

Page 35: C++ Review - CmpE WEB

Classes in C++: Why Create Classes / Objects?

Keeps all related info (i.e., data) together

Refer to all the related info by one name

Protect the information

Hide methods that use or change the info

Keep methods together with their related info

CMPE 250 C++ Review September 28, 2016 35 / 102

Page 36: C++ Review - CmpE WEB

Example of Benefits of Creating an Object

Keeps all related info (i.e., data) together

Person thisPerson;Person thisPerson = new Person ("Leyla", "Gencer", 80);

Refer to all the related info by one name

thisPerson

Protect the information

lastName = "Akan"; //normally data members are private,//and member functions are public

CMPE 250 C++ Review September 28, 2016 36 / 102

Page 37: C++ Review - CmpE WEB

Classes and Objects

CMPE 250 C++ Review September 28, 2016 37 / 102

Page 38: C++ Review - CmpE WEB

Example of a Simple Class

class Change{private:

int quarters;int dimes;

public:int getQuarters(){return quarters;}int getDime(){return dimes;}

void printChange(){

cout << "\nQuarters: " << quarters<< " Dimes: "<< dimes << endl;

}

};

CMPE 250 C++ Review September 28, 2016 38 / 102

Page 39: C++ Review - CmpE WEB

More Class Example

class human{

// this data is private to instances of the classint height;char name[];int weight;

public:void setHeight(int heightValue);int getHeight();

};

CMPE 250 C++ Review September 28, 2016 39 / 102

Page 40: C++ Review - CmpE WEB

Function Definitions

void human::setHeight(int heightValue){

if (heightValue > 0)height = heightValue;

elseheight = 0;

}

int human::getHeight(){

return(height);}

CMPE 250 C++ Review September 28, 2016 40 / 102

Page 41: C++ Review - CmpE WEB

Example

Code

// first we define the variables.int height = 180;int result = 0;human hasan;

//set our human’s heighthasan.setHeight(height);

//get his heightresult = hasan.getHeight();

cout << "Hasan is = " << result<< "cm tall" << endl;

OutputHasan is 180 cm tall

CMPE 250 C++ Review September 28, 2016 41 / 102

Page 42: C++ Review - CmpE WEB

Instantiating an Object

The class definition does not create any objects

Instantiating and constructing are equivalent words for building a newobject based on the model (i.e., template) of the class

Instantiating is done just like declaring a variable of a built in data type

Instantiating is done by a constructor (sometimes called a constructormethod)

If the "class provider" does not provide a constructor, then the C++compiler provides a default one automaticallyThe default constructor does not provide values to the data members(i.e. the instance variables)

CMPE 250 C++ Review September 28, 2016 42 / 102

Page 43: C++ Review - CmpE WEB

Instantiating an Object (Cont.)

When the object is instantiated, memory is allocated

Example of instantiation (implicit call of constructor)Car myCar;Elephant oneElephant, twoElephant;

No initialization takes place

Each object has its own memory allocation

oneElephant and twoElephant are separate objects in differentlocations in memory

Each is addressed individually by name or location

Each data member is addressed individually using the object nameand the data member name, for example:oneElephant.agetwoElephant.name

CMPE 250 C++ Review September 28, 2016 43 / 102

Page 44: C++ Review - CmpE WEB

Referencing an Object

Each object has a name (or a location) which is assigned when theobject is instantiated

private data members are accessible only within the class

since most data members are private, that means that these data itemsare accessed generally by means of member functionsmyElephant.age = 72; //won’t work, assuming age//is declared as privatemyElephant.setAge(72); // will work

CMPE 250 C++ Review September 28, 2016 44 / 102

Page 45: C++ Review - CmpE WEB

Inheritance

CMPE 250 C++ Review September 28, 2016 45 / 102

Page 46: C++ Review - CmpE WEB

Inheritance

The power of object-oriented languages

Enables reuse of fields/methods

All parent fields included in child instantiationProtected and public fields and methods directly accessible to childParent methods may be overriddenNew fields and methods may be added to the childMultiple inheritance

CMPE 250 C++ Review September 28, 2016 46 / 102

Page 47: C++ Review - CmpE WEB

Inheritance (cont’d)

class classname: public parentname {private:

...;public:

...;//access to parent methods through// parentname::methodname

}

CMPE 250 C++ Review September 28, 2016 47 / 102

Page 48: C++ Review - CmpE WEB

Header file

CMPE 250 C++ Review September 28, 2016 48 / 102

Page 49: C++ Review - CmpE WEB

Header file

For complex classes, the member functions are declared in a headerfile and the member functions are implemented in a separate file.

This allows people to look at the class definitions, and their memberfunctions separately

The header file needs to be included in your program when you usethe classes defined in the header file

CMPE 250 C++ Review September 28, 2016 49 / 102

Page 50: C++ Review - CmpE WEB

#include

CMPE 250 C++ Review September 28, 2016 50 / 102

Page 51: C++ Review - CmpE WEB

Header Guards

#ifndef __SEGMENT_HEADER__#define __SEGMENT_HEADER__

// contents of Segment.H//...

#endif

To ensure it is safe to include a file more than once

CMPE 250 C++ Review September 28, 2016 51 / 102

Page 52: C++ Review - CmpE WEB

Header Guards

CMPE 250 C++ Review September 28, 2016 52 / 102

Page 53: C++ Review - CmpE WEB

Input/Output

CMPE 250 C++ Review September 28, 2016 53 / 102

Page 54: C++ Review - CmpE WEB

Output

#include<iostream>Tell compiler that we are doing I/OcoutObject to which we can send data.«operator for sending data.endl \n \tSpecial symbols that we can send.

CMPE 250 C++ Review September 28, 2016 54 / 102

Page 55: C++ Review - CmpE WEB

Formatting Output

cout.setf(long flag) Set different formatting parameters for nextoutput.cout.unsetf(long flag) Disable these formatting parameters.

ios::left left justify the outputios::right right justify the outputios::scientific use scientific notation for numbersios::hex print numbers in hexadecimal baseios::dec print numbers in decimal baseios::uppercase print all characters in upper case

CMPE 250 C++ Review September 28, 2016 55 / 102

Page 56: C++ Review - CmpE WEB

Example

Code

#include<iostream>using namespace std;

int main(){

cout.width(10); //sets width to 10cout << "hello" << endl;cout.setf(ios::left);cout << "hello" << endl;

cout << 16 << endl;cout.setf(ios::hex, ios::basefield);cout << 16 << endl;

return 0;}

Outputhello

hello1610

CMPE 250 C++ Review September 28, 2016 56 / 102

Page 57: C++ Review - CmpE WEB

Input

#include<iostream>Tell compiler that we are doing basic I/OcinThe input object. It retrieves input from the keyboard.»The extractor operator.

CMPE 250 C++ Review September 28, 2016 57 / 102

Page 58: C++ Review - CmpE WEB

Example

Code

#include<iostream>using namespace std;

int main(){

int userInput;cout << "Enter number:";cin >> userInput;cout << "You entered " << userInput <<

endl;

return 0;}

OutputEnter number:12345You entered 12345

CMPE 250 C++ Review September 28, 2016 58 / 102

Page 59: C++ Review - CmpE WEB

I/O From a File

I/O from a file is done in a similar way.

#include<iostream>#include<fstream>using namespace std;

int main(){

int inputNumber;

ofstream myOutputFile("outfile");ifstream myInputFile("infile");myOutputFile << "text to file." << endl;myInputFile >> inputNumber;myOutputFile.close();myInputFile.close();

return 0;}

CMPE 250 C++ Review September 28, 2016 59 / 102

Page 60: C++ Review - CmpE WEB

I/O From File Example#include <string>#include <fstream>#include <iostream>#include <iomanip>using namespace std;

int main(int argc, char *argv[]){

string text;.// Check inputif(argc<2){

cout<<"Usage: "<<argv[0]<<" <filename>"<<endl;return 0;

}

// Try to read from filecout<<"Reading tokens from file ’"<<argv[1]<<":"<<endl;ifstream in(argv[1]);if(!in)

cout<<" - Could not read from file ’"<<argv[1]<<"’."<<endl;else{

string token;cout.setf(ios::right);for(unsigned i=1; in>>token; i++)

cout<<setw(4)<<i<<": "<<token<<endl;}in.close();cout<<endl;

CMPE 250 C++ Review September 28, 2016 60 / 102

Page 61: C++ Review - CmpE WEB

I/O From File Example

// Allow user to enter a tokenstring text;cout<<"Enter some text: ";getline(cin, text);

// Append new tokens to fileofstream out(argv[1], ios::app);if(out)

out<<endl<<text<<endl;else

cout<<"- Could not write to file "<<argv[1]<<" "<<endl;out.close();

return 0;}

CMPE 250 C++ Review September 28, 2016 61 / 102

Page 62: C++ Review - CmpE WEB

Memory

CMPE 250 C++ Review September 28, 2016 62 / 102

Page 63: C++ Review - CmpE WEB

What is a pointer?

int x = 10;int *p;

p = &x;

p gets the address of x in memory.

CMPE 250 C++ Review September 28, 2016 63 / 102

Page 64: C++ Review - CmpE WEB

What is a pointer?

int x = 10;int *p;

p = &x;

*p = 20;

*p is the value at the address p.

CMPE 250 C++ Review September 28, 2016 64 / 102

Page 65: C++ Review - CmpE WEB

What is a pointer?

CMPE 250 C++ Review September 28, 2016 65 / 102

Page 66: C++ Review - CmpE WEB

A Pointer Example

int main(){

int i, j;int *pi, *pj;

i = 5;j = i;pi = &i;pj = pi;

*pj = 4;

cout << i << " ";cout << j << " ";cout << *pi << " ";cout << *pj << endl;

return 0;}

Output4, 5, 4, 4

CMPE 250 C++ Review September 28, 2016 66 / 102

Page 67: C++ Review - CmpE WEB

Allocating memory using new

Point *p = new Point(5, 5);

Point is a class already defined

new can be thought of a function with slightly strange syntax

new allocates space to hold the object.

new calls the object’s constructor.

new returns a pointer to that object.

CMPE 250 C++ Review September 28, 2016 67 / 102

Page 68: C++ Review - CmpE WEB

Memory Allocation Examples

new returns a pointer to the dynamically created object.

#include "Cow.h"#include <iostream>using namespace std;

int main(){int *i = new int(12);Cow *c = new Cow;...delete i;delete c;

return 0;}

CMPE 250 C++ Review September 28, 2016 68 / 102

Page 69: C++ Review - CmpE WEB

Problems

Dangling pointers

Pointers to memory that has already been deallocatedsegmentation fault (core dump)... or worse....

Memory leakLoosing pointers to dynamically allocated memorySubstantial problem in many commercial productsC++ HAS NO GARBAGE COLLECTION!

CMPE 250 C++ Review September 28, 2016 69 / 102

Page 70: C++ Review - CmpE WEB

Dangling pointer examples

int main(){int *myNum = new int(12);int *myOtherNum;myOtherNum=myNum;

delete myNum;

cout << *myOtherNum << endl;

return 0;}

CMPE 250 C++ Review September 28, 2016 70 / 102

Page 71: C++ Review - CmpE WEB

Dangling pointer examples

int* badFunction(){int num = 10;return &num;

}int* stillBad(int n){

n += 12;return &n;

}int main(){

int num = 12;int *myNum = badFunction();int *myOtherNum = stillBad(num);

cout << *myNum << ", ";cout << *myOtherNum << endl;

return 0;}

CMPE 250 C++ Review September 28, 2016 71 / 102

Page 72: C++ Review - CmpE WEB

Memory Leak Examples

int main(){int *myNum = new int(12);myNum = new int(10);// Oops...

delete myNum;

return 0;}

CMPE 250 C++ Review September 28, 2016 72 / 102

Page 73: C++ Review - CmpE WEB

Memory Leak Examples

int evilFunction(){int *i = new int(9);return *i;

}

int main(){int num = evilFunction();

// I am loosing my memory!!

return 0;}

CMPE 250 C++ Review September 28, 2016 73 / 102

Page 74: C++ Review - CmpE WEB

Deallocating memory using delete

// allocate memoryPoint *p = new Point(5, 5);

...// free the memorydelete p;

For every call to new, there must be exactly one call to delete.

CMPE 250 C++ Review September 28, 2016 74 / 102

Page 75: C++ Review - CmpE WEB

Using new with arrays

int x = 10;int* nums1 = new int[10]; // okint* nums2 = new int[x]; // ok

Initializes an array of 10 integers on the heap.

CMPE 250 C++ Review September 28, 2016 75 / 102

Page 76: C++ Review - CmpE WEB

Using new with multidimensional arrays

int x = 3, y = 4;int* nums3 = new int[x][4][5];// okint* nums4 = new int[x][y][5];// BAD!

Initializes a multidimensional array

Only the first dimension can be a variable. The rest must beconstants.

Use single dimension arrays to fake multidimensional ones

CMPE 250 C++ Review September 28, 2016 76 / 102

Page 77: C++ Review - CmpE WEB

Using delete on arrays

// allocate memoryint* nums1 = new int[10];int* nums3 = new int[x][4][5];

...// free the memorydelete[] nums1;delete[] nums3;

Have to use delete[] .

CMPE 250 C++ Review September 28, 2016 77 / 102

Page 78: C++ Review - CmpE WEB

Big three: destructor, copy constructor, and assignment operator

CMPE 250 C++ Review September 28, 2016 78 / 102

Page 79: C++ Review - CmpE WEB

Class Destructors

If a class dynamicallyallocates memory, weneed a way to deallocateit when it’s destroyed.

Destructors called upondestruction of an object

class MyClass{public:

MyClass(){// Constructor

}~MyClass(){ //

Destructor}

...};

CMPE 250 C++ Review September 28, 2016 79 / 102

Page 80: C++ Review - CmpE WEB

Destructors

delete calls the object’s destructor.

delete frees space occupied by the object.

A destructor cleans up after the object.

Releases resources such as memory.

CMPE 250 C++ Review September 28, 2016 80 / 102

Page 81: C++ Review - CmpE WEB

Destructors – an Example

class Segment{public:

Segment();~Segment();

private:Point *m_p0, *m_p1;

};

CMPE 250 C++ Review September 28, 2016 81 / 102

Page 82: C++ Review - CmpE WEB

Destructors – an Example

Segment::Segment(){

m_p0 = new Point(0, 0);m_p1 = new Point(1, 1);

}Segment::~Segment(){

delete m_p0;delete m_p1;

}

CMPE 250 C++ Review September 28, 2016 82 / 102

Page 83: C++ Review - CmpE WEB

Copy Constructor

class Rooster{public:

...Rooster(const Rooster &rhs){

// Do your deep copy}...

};...// UsageRooster r(12);Rooster s(r);

CMPE 250 C++ Review September 28, 2016 83 / 102

Page 84: C++ Review - CmpE WEB

Assignment Operator

class Rooster{public:

...Rooster&operator=(const Rooster &rhs){

// Copy stuff}...

};...// UsageRooster r(12), s(10);r = s;

CMPE 250 C++ Review September 28, 2016 84 / 102

Page 85: C++ Review - CmpE WEB

Canonical Form

All classes should haveeach of the following:

Default constructorCopy constructorAssignment operatorDestructor

// Canonical Cowclass Cow{public:

Cow(){...}Cow(const Cow &rhs){...}Cow& operator=(const Cow &c)

{...}~Cow(){...}

...};

CMPE 250 C++ Review September 28, 2016 85 / 102

Page 86: C++ Review - CmpE WEB

Const

CMPE 250 C++ Review September 28, 2016 86 / 102

Page 87: C++ Review - CmpE WEB

Introducing: const

void Math::printSquare(const int& i){

i = i*i;cout << i << endl;

}int main(){

int i = 5;Math::printSquare(i);Math::printCube(i);

return 0;}

←Won’t compile

CMPE 250 C++ Review September 28, 2016 87 / 102

Page 88: C++ Review - CmpE WEB

How does const work here?

void Math::printSquares(const int& j, int& k){

k = k*k; // Does this compile?cout << j*j << ", " << k << endl;

}int main(){

int i = 5;Math::printSquares(i, i);

return 0;}

CMPE 250 C++ Review September 28, 2016 88 / 102

Page 89: C++ Review - CmpE WEB

Returning const references is OK

CMPE 250 C++ Review September 28, 2016 89 / 102

Page 90: C++ Review - CmpE WEB

Namespaces

Namespaces are like packages in Java

Reduces naming conflicts

Most standard C++ routines and classes are under the stdnamespace

CMPE 250 C++ Review September 28, 2016 90 / 102

Page 91: C++ Review - CmpE WEB

using namespace

#include <iostream>...std::string question = "How do I prevent repetitive strain

injury?";std::cout << question << std::endl;

using namespace std;

string answer = "Type less.";cout << answer << endl

But, not in header files!

CMPE 250 C++ Review September 28, 2016 91 / 102

Page 92: C++ Review - CmpE WEB

Template

CMPE 250 C++ Review September 28, 2016 92 / 102

Page 93: C++ Review - CmpE WEB

Template

What exactly are templates for, and why learn them?Limited Generic Programming (polymorphism)

Some functions have the same semantic meaning for some (if not all)data types. For instance, a function print() should display asensible representation of anything passed in. Ideally, it should notneed to be rewritten for each possible type.

Less repetitive codeCode that only differs in the data type it handles does not have to berewritten for each and every data type you want to handle. It is easierto read and maintain, since one piece of code is used for everything.

CMPE 250 C++ Review September 28, 2016 93 / 102

Page 94: C++ Review - CmpE WEB

Example: a swap function

Problem: Many times, it is nice to be able to swap the values of twovariables. This function’s behavior is similar for all data types. Templatedfunctions let you do that – in most cases without any syntax changes.

Swap for integers

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

int c = a;a = b;b = c;

}

Swap for an arbitrary type T

template <typename T>void swap(T &a, T &b){T c = a;a = b;b = c;

}

Templated functions can be used with any type that supports assignmentand can be passed in as a non-const reference.

CMPE 250 C++ Review September 28, 2016 94 / 102

Page 95: C++ Review - CmpE WEB

Template Syntax: Using it

Syntax example

double d1 = 4.5, d2 = 6.7;swap(d1, d2);

template <typename T>void swap(T &a, T &b){T c = a;a = b;b = c;

}

CMPE 250 C++ Review September 28, 2016 95 / 102

Page 96: C++ Review - CmpE WEB

Class Templates: Example

// CLASS TEMPLATE DEFINITIONtemplate<class ItemType> // formal parameter listclass StackType{public:

StackType(int max ); // max is stack sizeStackType(); // Default size is 500~StackType();bool IsEmpty( ) const;bool IsFull( ) const;void Push( ItemType item );void Pop( ItemType& item );ItemType Top( );

private:int top;int maxStack; // Maximum number of stack items.ItemType* items; // Pointer to dynamically// allocated memory

};

CMPE 250 C++ Review September 28, 2016 96 / 102

Page 97: C++ Review - CmpE WEB

Class Templates: Example

// Implementation of member function templates

template<class ItemType>StackType<ItemType>::StackType(int max){

maxStack = max;top = -1;items = new ItemType[maxStack];

}template<class ItemType>StackType<ItemType>::StackType(){

maxStack = 500;top = -1;items = new ItemType[maxStack];

}

CMPE 250 C++ Review September 28, 2016 97 / 102

Page 98: C++ Review - CmpE WEB

Class Templates: Example

template<class ItemType>bool StackType<ItemType>::IsEmpty() const{

return (top == -1);}template<class ItemType>bool StackType<ItemType>::IsFull() const{

return (top == maxStack-1);}template<class ItemType>void StackType<ItemType>::Push(ItemType newItem){

if (IsFull())throw FullStack();

top++;items[top] = newItem;

}

CMPE 250 C++ Review September 28, 2016 98 / 102

Page 99: C++ Review - CmpE WEB

Class Templates: Example

template<class ItemType>void StackType<ItemType>::Pop(){

if( IsEmpty() )throw EmptyStack();

top--;}template<class ItemType>ItemType StackType<ItemType>::Top(){

if (IsEmpty())throw EmptyStack();

return items[top];}template<class ItemType>StackType<ItemType>::~StackType(){

delete [] items;}

CMPE 250 C++ Review September 28, 2016 99 / 102

Page 100: C++ Review - CmpE WEB

Class Templates: Example

// Templated StackType class variables declaredStackType<int> myStack(100);// Stack of at most 100 integers.StackType<float> yourStack(50);// Stack of at most 50 floating point values.StackType<char> aStack;// Stack of at most 500 characters

CMPE 250 C++ Review September 28, 2016 100 / 102

Page 101: C++ Review - CmpE WEB

Compilation Model

PreprocessorResolves all preprocessor directives#include, #define macros, #ifdef, etc.

CompilerConverts text into object filesMay have unresolved interobject references

LinkerResolves all interobject references (or gives you a linker error)Creates the binary executable

LoaderLoads the program into RAM and runs the main() function

CMPE 250 C++ Review September 28, 2016 101 / 102

Page 102: C++ Review - CmpE WEB

Compilation

CMPE 250 C++ Review September 28, 2016 102 / 102