1.22k likes | 1.23k Views
C++ For Physics S. Brisbane Based on original slides I. Miller. IT Learning Group. What you know already…. Nothing is assumed. What you should have. Now: Setup instructions for the computers in today’s teaching labs At least the first part of the C++ generic workbook through to chapter 10
E N D
C++ For Physics S. BrisbaneBased on original slidesI. Miller IT Learning Group
What you know already… • Nothing is assumed
What you should have • Now: • Setup instructions for the computers in today’s teaching labs • At least the first part of the C++ generic workbook through to chapter 10 • A copy of these slides • The teaching materials are available from: • http://www-pnp.physics.ox.ac.uk/~brisbane/cplusplus_latest/
C++ and OOP? Compilers ISO and ANSI Standard C++ Library The Standard Template Library (STL ) Dev-C++/Eclipse Today's Topics First Program Fundamental data types Functions References Overloading functions Classes
What is OOP? • Object Oriented Programming • A way of modelling individual objects in the real world • Students • Vehicles • Buildings • ATM’s • etc, etc
So, what is OOP? • Natural thinking – making our C++ code do what we expect something to do in real life. • Class • Member functions/methodsrepresent real object - behaviour • Member variables/data membersrepresent real object - state
Editor Disk Add source Code Pre-processor Disk Directives allow add contents from ext files or constants Compiler Disk Convert the high level language into object code Linker Disk Link object code to library code & create exec code Memory Load from disk into memory Loader Disk Execution, CPU executes the program CPU Creating a C/C++ program
Why Compile? English talk “Add 17 and 9 please” “Johann Strauss” I’m sorry but I don’t understand English just binary talk, 1’s and 0’s. 001010100111 011011000110 100110110011 111100100000 100000111110
Why Compile? C++ Talk C O M P I L E R cout<<"Enter the first number: "; cin >>Num1; cout<<"Enter the second number: "; cin >>Num2; cout<<"The two numbers added = "<<Num1 + Num2; Binary Talk Enter the first number: 17 111001101111 001010100111 011011000110 100110110011 111101011111 Enter the second number: 9 The two numbers added = 26 Monitor
C++ Compilers • Many and varied • Sun Studio 10 Solaris, Linux • VisualAge C++ Linux • GCC Multi-platform • Microsoft Visual C++ Windows • Cygwin Linux • Dev-C++ Windows • Xcode Apple
C++ standard • Specification for the core C++ language • Types • Syntax • In addition to the core language, C++ has the “STL” • Class definitions for standard data structures • Collection of algorithms used to manipulate these and other structures • A compiler should support the standard
Compiler Conformance • There is no C++ compiler or library today that implements the Standard perfectly. • GCC >=4.8 is very close. * • Nothing in this course require the extra features introduced in C++11. • *GCC is mostly language-complete, but the standard library is missing a few aspects. • *https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2011
Working environment • I will use an Integrated Development Environment • Concentrate on the language rather than managing the environment • Speed up error checking • Makes creation of some template projects rather straightforward • Use of eclipse as IDE Focus on writing code and not managing code
Other Resources • There are other things to think about besides writing code • Manage the various versions of source code, see: • http://www2.physics.ox.ac.uk/it-services/svn-for-beginners • Which libraries and headers to build and include in your program • A tutorial I used to give going into more detail around libraries, objects headers and compilers • Take you through the basics • Finish with creating a small program from scratch that integrates with the root libraries and is managed by a “Makefile” • http://www-pnp.physics.ox.ac.uk/~brisbane/Teaching/Makefiles/index.html
First Program #include <iostream> using namespace std; intmain() { intaNum= 0; cin>> n; cout<< “Your number is: ” << n << endl; return 0; }
First Program #include <iostream> • Include contents of the header file in the program using namespace std; • cinis standard input stream object of istream class that allows input from keyboard • coutis standard output stream object, output to screen intmain() • In every C++ program, function
First Program intaNum= 0; • variable (memory location called aNum) to hold number of type integer (int) << (the stream insertion operator) cout<<“Enter a number:- ”; >> (the stream extraction operator ) cin>> aNum; First program
Comments • In C++, any text prefixed with the comment symbol (//) is an instruction to the pre-processor not to include code following the comment in the program. • It acts until the next line break • int main() //This is a comment about main • Multi-line comments use the /* to open a comment and */ to close
Basic Types • int//integer • char // ASCII character or 8–bit signed integer • float //single precision floating point number • double //double precision floating point number • bool // boolean – either true of false • unsigned float/int/char unsigned version of the above • void something with no type or return value
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”; elseelse 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 (Test) { case1: cout<<“Number1”; break; default: cout<<“NOT Number1”; } IfSwitchproject
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 relational operator == is an equality operator
Basic Control Flow • Repetition • while statement while(some condition is true) do the statements; while (counter < 4) { cout<<"Enter mark "; cin >> mark; total = total + mark; counter ++; }
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 project
Functions • Used to encapsulate data and operations • Can simplify coding • Functions for discrete tasks • Not hundreds of lines of code • Compiler only needs 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) voidreadChar(); intgetNumber(); doublenumDoubled(int);
Functions • Defining a function (no return value) voidreadChar() { char aChar; cout << "Enter a CHARACTER: " ; cin >> aChar; cout << "Character is " << aChar << endl; return; }
Functions • Calling a function • With no return type • readChar(); • With return type “int” intreadNumber(); • intmyNum = 0; • myNum = readNumber(); • cout << “The integer returned is “<< myNum; Funcproject
Scopes • The syntax { and } means that you are opening and closing a scope. • It is a way of grouping statements together • Variables declared within the scope have no meaning outside the scope • Function scope (most languages have this) • Block scope (java/python programmers beware!) • class scope (later) • File scope (later)
Scope • intmyfunction () • { //open ‘function’ scope • if (true ) • { //open if block • intmynumber=10; //declare and initialize //mynumber variable inside the ‘if’ block scope • } //close if block • return mynumber; //error! • } //close funciton scope
Functions – passing data • Pass by Value • Copy of value passed to function • Pass by Reference • Address of value passed to function FuncRef project
Functions – pass by Value • Function arguments have been passed as value (copy) • Value outside function not changed • intsquareByValue (intnum) • { • return num*num; • } • “num” only exists inside function scope
Functions – pass by Reference • Function argument is the address of the variable • Function works with the variable • Value outside function is changed • intsquareByReference(int &numberRef) • { • numberRef *= numberRef; • } • numberRef is passed as a reference to some integer in the calling scope
Declaring References • Must be initialised when declared • Cannot be reassigned • int & xRef = z; initialised • int & yRef; not initialised • xRef = &w; cannot assign • Another c++ context dependency “=“ acts differently at initialization and assignment.
Overloading Functions • Two or more functions with the same name • Must have different parameters • Different number • Different kind • Combination of the two • Compiler determines which function to use, depending on the parameters OverloadingFunctions project
Classes and Objects • 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 Hain • Sarah Jones • Thomas carlyle • Jane Seymour • Create an instance (object) of class student studentPeter; studentSarah;
So, what is OOP? • Natural thinking – making our C++ code do what we expect something to do in real life. • Class • Member functions/methodsrepresent real object - behaviour • Member variables/data membersrepresent real object - state
Classes and Objects • Member functions • Called by objectName.functionName() Peter.displayName(); Peter.setCourseName(); • Data Members (variables of object) • Member functions used to access the data members • Peter.name;
Standard 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
Operator precedence Note: Abridged version :- Full table in workbook
Exercises • Suggested exercises: • Set up working environment for today/next week • The “Getting Started” hand-out • Ex1, Ex2(a+b), Ex3 tasks 1-4, Ex4 • Those new to C/C++ please try to complete at least the starred(*) exercises today: • Ex5*, 6, 7*, 8*, 9*, 10*, 11*, 12*, 13*, • Ex14 task1-3, Ex15 task1, Ex16 task 1, ex17 task2 only, Ex22 T1&2, 23 T1&2 • It doesn’t matter which seat you pick today. Your account settings are automatically shared across all machines • Please sit in the same seat as last week
Creating classes Member functions and Data members Access specifiers Function Templates Pointers Interfaces Dynamic memory (a bit) Today’s Topics
Reminder, What is OOP? • Object Oriented Programming • A way of modelling individual objects in the real world • Students • Vehicles • Buildings • ATM’s • etc, etc
Reminder, what is OOP? • Natural thinking – making our C++ code do what we expect something to do in real life. • Class • Member functions/methodsrepresent real object - behaviour • Member variables/data membersrepresent real object - state
Classes and Objects • A class is a definition of a compound variable type • An object is an instance of that class • From a string class • Create many objects of type string • My Address • My Name • Create an instance (object) of class string • stringmyname; • stringmyaddress; • Or your own class ‘student’ i.e. studentpeter;
Classes and Inheritance • Allows creation of hierarchy of classes. • Start with abstract ideas • Detail specific classes • Allows reuse of code • Inherit properties • Base and derived classes • Encapsulation of data