Today's Topics Where is the fire exit? C++ and OOP? Flow Control - - PDF document

today s topics
SMART_READER_LITE
LIVE PREVIEW

Today's Topics Where is the fire exit? C++ and OOP? Flow Control - - PDF document

Today s arrangements C++ for Physics Your teacher is: Your demonstrators are: We finish at: You should have: Class notes Copies of slides IT Learning Group IT Learning Programme Your safety is important Today's Topics Where is the


slide-1
SLIDE 1

Oxford University Computing Services IT Learning Programme

IT Learning Programme

C++ for Physics

IT Learning Group

Today’ s arrangements

Your teacher is: Your demonstrators are: We finish at: You should have: Class notes Copies of slides

Your safety is important

Where is the fire exit? Beware of hazards

Tripping over bags and coats

Please tell us if anything does not work Let us know if you have any other concerns

Today's Topics

C++ and OOP? First Program Fundamental data types string class Functions Classes Member functions Data members Flow Control S equence S election Repetition Arrays Vectors Function Templat es Pointers

What is OOP?

Obj ect Oriented Programming

A way of modelling individual obj ects in the real world S tudents Vehicles Buildings ATM’ s

etc, etc

S

  • , what is OOP?

Combined variable type that includes functions

Class

Member functions/ methods represent real obj ect - behaviour Member variables/ data members represent real obj ect - state

slide-2
SLIDE 2

Oxford University Computing Services IT Learning Programme

S tandard C++ Library

  • Collection of classes and

functions

  • Result of conformance to ISO

standard

  • Incorporates what was STL
  • Class definitions for standard data

structures

  • Collection of algorithms used to

manipulate these and other structures

First Program

#include <iostream>

Include contents of the header file in the program

using namespace std;

cin is standard input stream obj ect of istream class t hat allows input from keyboard cout is standard output stream obj ect

int main()

In every C++ program, funct ion

First Program

int aNum = 0;

variable (memory location called aNum) to hold number

  • f type integer (int)

<< stream insertion operator cout <<“ Enter a number:- ” ; >> stream extraction operator cin >>aNum;

First program

Functions

Used to encapsulate data and operations

Can simplify coding

Functions for discrete tasks Not hundreds of lines of code

Only need to know

Input data Output data

Functions can be reused

Functions

Need a prototype

Tells the compiler what is coming

Return type Function name Parameter list (what is being passed in)

void readChar(); int getNumber(); double numDoubled(int);

Functions

Defining a function (no return value)

void readChar() { char aChar; cout << "Enter a CHARACTER: " ; cin >> aChar; cout << “Character is " << aChar << endl; return; }

slide-3
SLIDE 3

Oxford University Computing Services IT Learning Programme

Functions

Calling a function With no return type

readChar();

With return type int

int myNum = 0; myNum = readNumber(); cout << “The integer returned is “<< myNum;

CharNumStringFunc.dev

Functions

Pass by Reference Previously, pass by Value

Copy of value passed to function

Pass by Reference

Address of value passed to function

FuncRef.dev

Classes and Obj ects

A class is a definition of a compound variable type An object is an instance of that class From a student class

Create many objects of type student

Peter Sarah Thomas Jane

Create an instance (object) of class student

student Peter; student Sarah;

Classes and Obj ects

Member functions

Called by objectName.functionName()

Peter.displayName(); Peter.setCourseName(); Peter.setYears();

Data Members (variables of obj ect)

Member functions used to access the data members

Classes and Obj ects

Data Members

Access specifiers private: only accessible via member functions of the class protected: only accessed via member funct ions of the class and member functions of a derived class public: can be accessed from any (non-member) function, anywhere the obj ect is visible

Classes and Obj ects

class StudentCourse { private: string courseName; public: void setName(string name) { courseName = name; } };

OxStudents.dev

slide-4
SLIDE 4

Oxford University Computing Services IT Learning Programme

Classes and Obj ects

Constructors

Default constructors, provided by compiler Create your own & initialise data members

StudentCourse (string cName)

{

CourseName = cName; }

Destructors

Class name preceded by tilde ~ ~ StudentCourse ();

Classes and Obj ects

Separate class files for reusability

Class files with main() means the class cannot be reused. Only have one main() function Separate class into own file with .h suffix Use pre-processor directive to add the file when compiled #include “myClass.h”

Constructor.dev

Basic Control Flow

Sequence

What we have been doing already

Selection

if… else statements Two possible marks, 49 or 50 stored in score if(condition is true) if(score >= 50)

cout<<“ Passed” ; cout<<“ Passed” ;

else else

cout<<“ Failed” ; cout<<“ Failed” ;

Basic Control Flow

Selection

switch multiple selection statements

Test must be constant integer value, 1, 10, ‘A’, ‘x’. Not 10.56, 5.2.

switch (aNumb) { case 1: cout<<“ Number1” ; break; default: cout<<“ NOT Number1” ; }

IfSwitch.dev

Basic Control Flow

Repetition

The ‘for’ loop for (i = 1; i<= 5; i++)

{ do this statement; now do this statement; }

Note: = is an assignment <= is a relat ional operator == is an equality operator

Basic Control Flow

Repetition

while statement while(some condition is true) do the statements; while (counter < 4) { cout<<"Ent er mark "; cin >> mark; total +=mark; counter ++; }

slide-5
SLIDE 5

Oxford University Computing Services IT Learning Programme

Basic Control Flow

Repetition

do… while loop do { statements } while(the condition is true) do { cout<<“ Mark number " <<mark <<endl; mark ++; } while (mark <=10); DoWhile.dev

Exercises

Complete exercises in sections 1-8

Arrays

Data structure containing same type of data (int, double, string, char, object) Series of elements each containing one item of data (contiguous memory locations) Cannot change size

Element 1 2 3 4 5 Experiment Result 34.67 31.78 31.89 34.67 36.23 32.78

Arrays

int inNumbers[20];

an array of 20 integers

char inName[5];

an array of 5 characters

double examMarks[] = {1.2, 3.9, 9.5}

initialise and set size to 3 elements of type double

Arrays

Adding data to arrays. double examMarks[5] = {0};

for(int i = 0; i <5; i++) { cout<<"Enter Exam Mark "<<i + 1<<" "; cin >> examMarks[i]; }

Arrays

Outputting data from an array for(int i = 0; i <5; i++) {

cout<<"Exam Mark "<<i + 1<<"is "<< examMarks[i] <<endl;

}

Array.dev

slide-6
SLIDE 6

Oxford University Computing Services IT Learning Programme

Vectors

Container class, part of Standard Template Library, similar to arrays Can hold objects of same type of data (int, double, string, char, object) Can resize, grow, shrink as elements are added

  • r removed from the end

Algorithms to manipulate data Iterators (like pointers) to cycle through all elements in vector

Vectors

vector<int> vec(20,0); for(int i = 0; i<vec.size(); i++) vec[i] = (i); for(int i = 0; i<vec.size(); i++) { cout<< vec[i]<<" "; }

Vectors

Adding an extra element cout<<"Enter an Extra Value "; cin >> aNum; vec.push_back(aNum); Print vector of 21 numbers for(int i = 0; i<vec.size(); i++) { cout<< vec[i]<<" "; }

Vectors

Vector m em ber Function Effect at(elem ent num ber) Gets the value con tain ed in the specified elem ent back() Gets the value in the fin al elem ent begin() Points to the first elem ent in vecto r clear() Erases the vector em pty() Returns true (1) if the vecto r is em pty, or false (0 ) otherwise end() Points to the last elem en t in vecto r fron t() Gets the value in the first elem en t pop_ back() Rem oves the fin al elem en t push_ back(value) Adds an elem en t to the end o f the vector, con taining the specified value size() Gets the num ber of elem en ts reverse(); reverse(v.begin() v.end()) An algorithm (global function) that reverses the values in a vecto r (v) v.begin() and v.end() are iterato rs sort(); sort(v.begin(), v.end()) An algorithm (global function) that sorts the vecto r (v) v.begin() and v.end() are iterato rs

VectorPushBack.dev

Lists

Another container class also part of standard library. Can hold objects of same type of data (int or double or string or objects). Can resize, grow, shrink as elements are added or removed. Links to preceding & following elements. Efficient insertion and removal of elements anywhere in the container.

Lists

list<double> mylist(2,); mylist.push_back(7.8); mylist.push_back(23.2); mylist.push_front(67.62); mylist.push_front(2.73); mylist.pop_back() mylist.pop_front()

slide-7
SLIDE 7

Oxford University Computing Services IT Learning Programme

Lists

Output list elements (no subscript operator []) Looping through the list Need an iterator list<double>::iterator it;

for (it = mylist.begin(); it!=mylist.end(); ++it) cout << " " << *it; Merge.dev

Function Templates

One function definition Separate object code functions created,

Determined by argument Effectively many overloaded functions

template < typename T >

Value T is a type, not a value

T maximum( T value1, T value2, T value3 )

Function Templates

template < typename T > T maximum( T value1, T value2, T value3 ) { T maximumValue = value1; if ( value2 > maximumValue ) maximumValue = value2; if ( value3 > maximumValue ) maximumValue = value3; return maximumValue; } FunctionTemplate.dev ArraySortVectorTEMPLATEClass

Pointers

A pointer identifies a memory address

A pointer can be used to point to the location in memory where a variable is stored Variable: int a = 5; Pointer: int *ap; (*is dereference operator) NOTE: *used in declarations section indicates variable is a pointer, not a value *used before a pointer elsewhere in program, references the value at the address in memory

Pointers

Initialising pointers

int a = 5; int *ap; ap = &a; pointer ap now points to the address of variable a.

OR

int a = 5; int *ap = &a;

PointerArithmetic.dev

Exercises

Complete exercises in sections 9-12

slide-8
SLIDE 8

Oxford University Computing Services IT Learning Programme

IT Learning Programme

C++ for Physics - Day Two

Today's Topics

Values & References Inheritance Member initialiser list Overriding base class methods Friend Functions Friend Classes Composition Operator overloading Polymorphism Virtual member functions Non virtual member functions

Functions - Call by Value

Function arguments have been passed as value (copy) Value outside function not changed int squareByValue (int num) { return num*num; }

Functions - Call by Reference

Function argument is the address of the variable Function works with the variable Value outside function is changed int squareByReference(int &numberRef) { numberRef *= numberRef; }

Declaring References

Must be initialised when declared Cannot be reassigned int & xRef = z; initialised int & yRef;

not initialised

xRef = &w;

cannot reassign

Pointers?

Don’ t have to be initialised when declared Can be reassigned int *wPtr;

not initialised

wPtr = &w;

initialised

wPtr = &x;

can reassign

slide-9
SLIDE 9

Oxford University Computing Services IT Learning Programme

Reference Parameters and Classes

Void raise(Staff emp, double amt);

S taff obj ect emp double amt Function receiving S taff obj ect variable, not a reference, oh dear! What happens when the function runs?

Classes

Inheritance Allows creation of hierarchy of classes. S tart with abstract ideas Detail specific classes Allows reuse of code Inherit properties Base and derived classes Inheritance Inheritance

Staff MD Accounts Manager Sales Manager Sales Staff Accounts Staff

Inheritance Syntax

class Sales Staff : public Staff {

Data members; Member functions;

}; S ales S taff class will inherit (have access to) all data members & member funct ions of S taff class

Inheritance

public:

Declared in a public section, members can be accessed from anywhere

private:

Declared in a private section, members can only be accessed by member functions and friends of the class

slide-10
SLIDE 10

Oxford University Computing Services IT Learning Programme

Inheritance

Protected:

Declared in a protected section, members can be accessed by:

member functions friends of the class member functions of derived class friends of derived classes

Inheritance Base and Derived Classes

class Manager : public Staff {

Data members; Member functions;

}; Base class is Staff Derived class is Manager

StaffNIL.dev

MemberInitialiser List

Manager::Manager(string name, string DOB, string DOJ, string po, string ns) :position(po), numStaff(ns), Staff(name, DOB, DOJ)

Preprocessor wrapper #indef

If class is not defined ‘ ifndef’ , define it If already defined, leave from compilation process

Initialiser List & ifndef - define

Exercises

Complete exercises in sections 14 – 15.5

Overriding Base Class Methods Derived class method must match base class

S ame name, return type and number of arguments

Beware: overriding base class methods can hide overloaded functions in base class

Inheritance

slide-11
SLIDE 11

Oxford University Computing Services IT Learning Programme

Friends and Functions

Derived classes can access members of base classes. Friend functions can do the same Declare the function as a friend in the class

friend Rectangle duplicate (Rectangle);

The external function can then access public and private members

Inheritance

Friends and Classes

Derived classes can access members of base classes. Friend classes can do the same Declare the class as a friend in the class

friend class Rectangle;

The external class has access public and private members

Inheritance

Composition or Aggregation

Including obj ects of other classes as data members

  • f the class

Composition

Operator Overloading

Give a different functionality to operator int a = 37; int b = 63; c = a + b; CVector d (3,1); CVector e (6,3); F = d + e;

Operator Overloading

Polymorphism

Pointers again! A pointer to a derived class is type compatible with a pointer to a base class! Can use the pointer to look at member functions of the base class OR member functions of derived classes Need a VIRTUAL FUNCTION

Polymorphism

virtual function

Member of a base class

Functionality

Can be overridden in derived classes Functionality in base class is replaced with a new set of implementation in the derived class

Functions in the derived class must have the same name

slide-12
SLIDE 12

Oxford University Computing Services IT Learning Programme

Polymorphism

Duck myDuck; Bird * Ptrb = &myDuck;

Bird pointer points to a Duck object

Pointer Ptrb can be used to access base and derived class functions, providing t he base class funct ion is a VIRTUAL function Declaring a function as virtual in the base class

virtual void talk() const; Virtual functions

Exercises

Complete exercises in sections 15.6 to 19

IT Learning Programme

C++ for Physics - Day Three

Today's Topics

Abstract classes S tatic binding Dynamic binding Pure virtual functions S TL Containers Algorithms Iterators

Abstract Classes

Classes t hat we never instantiate Derived classes contain detail implementation Base class data members and member funct ions might be difficult to define S

  • create an abstract class and t hen add the specifics in

the concret e class Make one of the virtual functions a pure virtual function virtual void area() = 0;

Abstract Classes

Payment could be declared as pure virtual in the Employees class as it is not possible to define the earnings for the three derived classes. Derived class functions contain implementation

Abstract Class

slide-13
SLIDE 13

Oxford University Computing Services IT Learning Programme

STL

Containers vectors lists deques multiset multimap algorithms

Exercises

Complete what you can.

IT Learning Programme

C++ for Physics