Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ For Physics S. Brisbane Based on original slides I. Miller

Similar presentations


Presentation on theme: "C++ For Physics S. Brisbane Based on original slides I. Miller"— Presentation transcript:

1 C++ For Physics S. Brisbane Based on original slides I. Miller
IT Learning Group

2 What you know already… Nothing is assumed
Oxford University Computing Services

3 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: ~brisbane/cplusplus_latest/

4 Today's Topics C++ and OOP? Compilers ISO and ANSI
Standard C++ Library The Standard Template Library (STL ) Dev-C++/Eclipse First Program Fundamental data types Functions References Overloading functions Classes Oxford University Computing Services

5 What is OOP? Object Oriented Programming
A way of modelling individual objects in the real world Students Vehicles Buildings ATM’s etc, etc My personal opinion is that despite its slightly slower execution speed, OOP, or Object Oriented Programming, is one the best programming concept invented -- just as good as the multitasking OS and compiled libraries. OOP is really just trying to model individual objects in the world. This allows for natural-thinking -- what you would expect something to do in real life also does the same thing in code. If programmed correctly you could basically end up "speaking English" to the objects in your program or game. Users of Visual BASIC or Visual C++ will pick up this since it is an object-oriented language -- each control in the GUI is a type of object. Moving into OOP is what changes programming from decipherable code into real, understandable thought that is easy to understand. You have to keep in mind that the computer thinks in specifics. In fact so specific that the only thing the computer truly understands (if understanding is proper terminology) is "electrical signal on." Perhaps not even "off" as that is simply the absence of an "on," but that's a matter of philosophy. Another method of looking at OOP, which is just as valid, is inheritance. And instead of looking from the big to the small, you look from the generic to the specific. Try to start as generic as common sense dictates. Let's use "vehicle" as an example. What do all vehicles have in common? They all have tires and engines right? Wrong. Helicopters are vehicles and don't have tires and glider planes don't have engines. The computer takes everything 100% literally, so you have to be as specific as possible when planning your programming project. All vehicles can move -- that's what makes them vehicles. Now in our "real world," this matters worth squat since all matter can move but for a computer an object that can move can do something, and anything that happens needs to be coded. To continue, think up more specific groups, like cars, which share tires, engines, and more, and even farther to say four- door and two-door, then to specific models like a Nissan Micra, which has all of the previous features in common but has unique characteristics such as X horsepower and X size fuel tank. The point of doing this is for breaking down many complex objects and tasks into simpler subgroups which can be programmed by themselves and then used in all objects following that one. For example you could program an engine then anything that has an engine in it will use that code when they run their engine.

6 What is OOP? Sequence of commands, procedural (C, PASCAL) – No
Commands combined into functions – Yes Variables – Yes Compound variables, like structures in ‘C’ – sort of Oxford University Computing Services

7 So, what is OOP? Natural thinking – making our C++ code do what we expect something to do in real life. Class Member functions/methods represent real object - behaviour Member variables/data members represent real object - state Oxford University Computing Services

8 Creating a C/C++ program
Editor Pre-processor Compiler Linker Loader CPU Disk Memory Add source Code Directives allow add contents from ext files or constants Convert the high level language into object code Link object code to library code & create exec code Load from disk into memory Execution, CPU executes the program What is a compiler? This is not a silly question. We were all beginners at one time and asked the same question. The following answer is provided for those that have no programming experience. A computer cannot understand the spoken or written language that we humans use in our day to day conversations, and likewise, we cannot understand the binary language that the computer uses to do it's tasks. It is therefore necessary for us to write instructions in some specially defined language, in this case C++, which we can understand, then have that very precise language converted into the very terse language that the computer can understand. This is the job of the compiler. A C++ compiler is itself a computer program who's only job is to convert the C++ program from our form to a form the computer can read and execute. The computer prefers a string of 1's and 0's that mean very little to us, but can be very quickly and accurately understood by the computer. The original C++ program is called the "source code", and the resulting compiled code produced by the compiler is usually called an "object file". One or more object files are combined with predefined libraries by a linker to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled "object code" that provides operations that are done repeatedly by many computer programs. Any good compiler that you purchase will provide not only a compiler, but an editor, a debugger, a library, and a linker. Online documentation and help files are usually included, and many compilers have a tutorial to walk you through the steps of compiling, linking and executing your first program. The most common reason for wanting to translate source code is to create an executable program. The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine language). Preprocessor: Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. These lines are always preceded by a pound sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements. These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\). Pre-processing in C/C++ The most widely used lexical preprocessor is CPP, the C preprocessor, used pervasively in C and its descendant, C++. This preprocessor is used to provide the usual set of preprocessing services The most common use of the C preprocessor is the #include "..." or #include <...> directive, which copies the full content of a file into the current file, at the point at which the directive occurs. These files usually (almost always) contain interface definitions for various library functions and data types, which must be included before they can be used; thus, the #include directive usually appears at the head of the file. The files so included are called "header files" for this reason. Some examples include <math.h> and <stdio.h> from the standard C library, providing mathematical and input/output functions, respectively. While this use of a preprocessor for code reuse is simple, it is also slow, rather inefficient and requires the additional use of conditional compilation to avoid multiple inclusions of a given header file. Since the 1970s, faster, safer and more efficient alternatives to reuse by file inclusion have been known and used by the programming language community, and implemented in most programming languages: Java and Common Lisp have packages, Pascal has units, Modula, OCaml, Haskell or Python have modules, and D, designed as a replacement of C and C++, has imports. // Source Code The Source Code for a typical C++ program consists of one or more header files, which usually have the suffix .h or .hh These usually contain declarations of variables, functions and classes. Header files are either provided by the programmer or supplied with the compiler, operating system or some external package. They allow the programmer to access standard library functions. e.g. the maths functions sin(), cos() etc. The C++ Source Files , which usually have the suffix .cpp or .C contain the implementations (definitions) of the functions etc declared in the header files. i.e the actual lines of C++ code. What happens when the “Compiler” is run? To produce an executable program from the source code requires a 3-stage process. The first 2 steps are carried out independently for each .cpp file. (1) Pre-process: First the C pre-processor (cpp) is run on each source (.cpp) file. This interprets pre-processor directives, which are indicated by the # symbol. The most important of these is the #include statement. The statement #include "afile.h" places the contents of the local header file "afile.h" in the body of the code. Whilst #include <afile.h> places the contents of the standard header file afile.h in the code. (2) Compile: The expanded source code file resulting from pre- processing (translation unit) is compiled to produce an object file (suffix .obj or .o) containing the raw machine instructions. (3) Linking: The Linker (Loader) combines one or more object files together with standard libraries (which contains collection of object files) to produce an executable (suffix .exe or no suffix). This is the program that one actually runs. Oxford University Computing Services

9 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. Oxford University Computing Services

10 Why Compile? C++ Talk C O M P I L E R Binary Talk
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 Enter the second number: 9 The two numbers added = 26 Monitor Oxford University Computing Services

11 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 Oxford University Computing Services

12 Specification for the core C++ language Types Syntax
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 To make a computer do anything, you have to write a computer program. When you write this program you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal When you are telling the computer what to do, you also get to choose HOW it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. You get off a plane and want to get home, how do you do it? The taxi algorithm: Go to the taxi stand. Get in a taxi. Give the driver my address. The rent-a-car algorithm: Take the shuttle to the rental car place. Rent a car. Follow the directions to get to my house. The bus algorithm: Outside baggage claim, catch bus number 70. Transfer to bus 14 on Main Street. Get off on Elm street. Walk two blocks north to house.

13 Compiler Conformance ISO International Standards Organisation
ANSI - American National Standards Institute Standard C++98 C++2003 2005 Library Technical Report 1 C++11 Compilers and standard library implementations should support these standards Language standard After years of work, a joint ANSI–ISO committee standardized C++ in 1998 (ISO/IEC 14882:1998). For some years after the official release of the standard, the committee processed defect reports, and published a corrected version of the C++ standard in In 2005, a technical report, called the "Library Technical Report 1" (often known as TR1 for short) was released. While not an official part of the standard, it gives a number of extensions to the standard library which are expected to be included in the next version of C++. Support for TR1 is growing in almost all currently maintained C++ compilers. While the C++ language is royalty-free, the standard document itself is not freely available. One approach to measuring the conformance of a compiler to a Standard is to construct a suite of test cases that measure either the acceptance of correct code or the rejection of incorrect code. However, constructing such test suites is difficult because there are no central repositories of test cases that conform to the Standard. Of course, you could build test cases using coding examples listed on the Web, but these coding examples are likely designed for specific compilers and, therefore, exhibit bias. An alternative approach is to extract test cases from examples in the ISO C++ Standard; Convergence of the Standard Our goals in choosing the ISO Standard as the source of our test suite were to: Build a test suite that covered the important issues for compilation of C++ programs. Obtain test cases that were unbiased toward any particular compiler or vendor. Use the Standard as an oracle to determine the validity and outcome of the test cases. While our extracted test suite meets the first two goals, the third goal is more elusive. The examples described in the Standard are intended to illustrate intricate facets of C++ language syntax or semantics—they aren't intended to be programs. Therefore, conversion of the examples into compilable programs, in most cases, requires some interpretation. Moreover, a surprising number of examples in the Standard contain errors. Some of these errors have been reported with suggested corrections, others are still under debate, and others seem to have been overlooked. Oxford University Computing Services

14 Why Conformance? Need an official standard
To understand which compiler and standard library implementations support the standard Code that works correctly under more than one compiler Developer can have some degree of assurance that programs will run on whatever platform they might need to target Oxford University Computing Services

15 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. * Oxford University Computing Services

16 I will use an Integrated Development Environment
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

17 Other Resources There are other things to think about besides writing code Manage the various versions of source code, see: 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”

18 Questions so far?

19 First Program #include <iostream> using namespace std;
int main() { int aNum = 0; cin >> n; cout << “Your number is: ” << n << endl; return 0; } Standard Library Header Files The standard library is divided into many parts and each has its own header file. The header files contain the function prototypes for the related functions that form each part of the library. The header files also contain definitions of various class types and functions, as well as constants needed by the functions. A header file “instructs” the compiler on how to interface with library and user-written components. #include <iostream> This header file contains function prototypes for the C++ standard input and output functions. #include <cstdlib> This header file contains function prototypes for conversions of numbers to text, text to numbers, memory allocation, random numbers and various other utility functions. #include <iomanip> This header file contains function prototypes for stream manipulation that format streams of data. #include <iomath> This header file contains function prototypes for math library functions. #include <cctype> This header file contains function prototypes that test characters for certain properties (whether a character is a digit or a punctuation) and other prototypes for functions to convert lowercase letters to upper and vice versa. using, namespace, and std The next line, using namespace std, will be present in nearly all of our programs. It tells the compiler to treat the names in the standard library, a very important part of the C++ language definition, as though we had defined them in the current program. These names from the standard library include string, which is why we need using namespace std; here. I'll go into this in much more detail later, but in the meantime, here's a little information about using, namespace, and std. A namespace is a collection of identifiers (variable names and some other types of names that we haven't discussed yet) that all belong to a "family" of sorts. To refer to a specific identifier that belongs to a namespace, you can prefix the identifier with the name of the namespace followed by two colons. For example, all of the identifiers in the C++ standard library are in the namespace called std. So, for example, if we want to refer to the version of string that is in the namespace called std, we can refer to it by the name std::string. However, because the standard library identifiers are used so frequently, it is annoying to have to say std:: every time we want to refer to one of them. The designers of the language have anticipated this problem and have provided the using facility to allow us to write our programs in a more natural way. What using means is that we want the compiler to add a certain name or set of names from a particular namespace to the currently accessible set of names. In this particular case, using namespace std; means that we want the compiler to make all the names in the standard library accessible. If we left that line out, whenever we wanted to create a variable of string type, we would have to write std::string rather than just string, and the same would be true of the other types defined in the standard library that we will be using later. I think we have enough details to keep track of without having to worry about that particular one, so I have included the line using namespace std; in all of the example programs except where I have a specific reason not to do so; I'll note those cases when we get to them. When we say using namespace std;, that means "add the names from the standard library to the names we have available for use". For example, after that statement, if I say cout, I mean std::cout, and if I say string, I mean std::string (:: scope resolution operator). Names not defined in the standard library aren't affected by this. It's only things that have names defined in the standard library that are affected. However, if you have something called "string", for example, that is defined in the standard library and also in your code, you can say "::string" if you don't want to use the one from the standard library. cin Standard input stream cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin. cout Standard output stream cout is an object of class ostream that represents the standard output stream. It corresponds to the cstdio stream stdout. Oxford University Computing Services

20 First Program #include <iostream> using namespace std;
Include contents of the header file in the program using namespace std; cin is standard input stream object of istream class that allows input from keyboard cout is standard output stream object, output to screen int main() In every C++ program, function Standard Library Header Files The standard library is divided into many parts and each has its own header file. The header files contain the function prototypes for the related functions that form each part of the library. The header files also contain definitions of various class types and functions, as well as constants needed by the functions. A header file “instructs” the compiler on how to interface with library and user-written components. #include <iostream> This header file contains function prototypes for the C++ standard input and output functions. #include <cstdlib> This header file contains function prototypes for conversions of numbers to text, text to numbers, memory allocation, random numbers and various other utility functions. #include <iomanip> This header file contains function prototypes for stream manipulation that format streams of data. #include <iomath> This header file contains function prototypes for math library functions. #include <cctype> This header file contains function prototypes that test characters for certain properties (whether a character is a digit or a punctuation) and other prototypes for functions to convert lowercase letters to upper and vice versa. using, namespace, and std The next line, using namespace std, will be present in nearly all of our programs. It tells the compiler to treat the names in the standard library, a very important part of the C++ language definition, as though we had defined them in the current program. These names from the standard library include string, which is why we need using namespace std; here. I'll go into this in much more detail later, but in the meantime, here's a little information about using, namespace, and std. A namespace is a collection of identifiers (variable names and some other types of names that we haven't discussed yet) that all belong to a "family" of sorts. To refer to a specific identifier that belongs to a namespace, you can prefix the identifier with the name of the namespace followed by two colons. For example, all of the identifiers in the C++ standard library are in the namespace called std. So, for example, if we want to refer to the version of string that is in the namespace called std, we can refer to it by the name std::string. However, because the standard library identifiers are used so frequently, it is annoying to have to say std:: every time we want to refer to one of them. The designers of the language have anticipated this problem and have provided the using facility to allow us to write our programs in a more natural way. What using means is that we want the compiler to add a certain name or set of names from a particular namespace to the currently accessible set of names. In this particular case, using namespace std; means that we want the compiler to make all the names in the standard library accessible. If we left that line out, whenever we wanted to create a variable of string type, we would have to write std::string rather than just string, and the same would be true of the other types defined in the standard library that we will be using later. I think we have enough details to keep track of without having to worry about that particular one, so I have included the line using namespace std; in all of the example programs except where I have a specific reason not to do so; I'll note those cases when we get to them. When we say using namespace std;, that means "add the names from the standard library to the names we have available for use". For example, after that statement, if I say cout, I mean std::cout, and if I say string, I mean std::string (:: scope resolution operator). Names not defined in the standard library aren't affected by this. It's only things that have names defined in the standard library that are affected. However, if you have something called "string", for example, that is defined in the standard library and also in your code, you can say "::string" if you don't want to use the one from the standard library. cin Standard input stream cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin. cout Standard output stream cout is an object of class ostream that represents the standard output stream. It corresponds to the cstdio stream stdout. Oxford University Computing Services

21 First Program int aNum = 0; << (the stream insertion operator)
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; Built-in Stream Manipulators Manipulators (endl is one) are functions or function objects (also known as functors) that are inserted into or extracted from a stream; they affect the formatting of the objects that are used with that stream, or affect the stream itself in some way. Manipulators are used to control and set the state of the stream. String class: A minor gotcha. Though string is in the <string> library, you can also access it via the std namespace, however cout may not work with it. The C++ string class defines the global function getline() to read strings from an I/O stream. The getline() function, which is not part of the string class, reads a from the input stream object cin. For example, the following code reads a line of text from stdin and displays it to stdout: string s; getline( cin, s ); cout << "You entered " << s << endl; ci.ignore(); float fl; std::cin >> fl; char str[101]; std::cin.getline(str, 101); And you type: 3.14<return> 3.14 is read into fl . The newline following the 3.14 is still sitting on the input buffer. std::cin.getline(str, 101) immediately processes the newline that is still on the input buffer. str becomes an empty string. The illusion is that the application "skipped" the std::cin.getline() statement. The solution is to add std::cin.ignore(); immediately after the first std::cin statement. This will grab a character off of the input buffer (in this case, newline) and discard it. First program Oxford University Computing Services

22 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

23 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

24 Basic Control Flow Sequence Selection
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”; >= is a relational operator = = equality operators ! = equality operators Oxford University Computing Services

25 Basic Control Flow Selection switch multiple selection statements
Test must be constant integer value, 1, 10, ‘A’, ‘x’. Not , 5.2. switch (Test) { case 1: cout<<“Number1”; break; default: cout<<“NOT Number1”; } IfSwitch project Oxford University Computing Services

26 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 Oxford University Computing Services

27 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 ++; } Oxford University Computing Services

28 Basic Control Flow Repetition do…while loop do { statements }
while(the condition is true) cout<<“Mark number " <<mark <<endl; mark ++; while (mark <=10); DoWhile project Oxford University Computing Services

29 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 Oxford University Computing Services

30 Functions Need a prototype void readChar(); int getNumber();
Tells the compiler what is coming Return type Function name Parameter list (what is being passed in) void readChar(); int getNumber(); double numDoubled(int); Oxford University Computing Services

31 Functions Defining a function (no return value) void readChar() {
char aChar; cout << "Enter a CHARACTER: " ; cin >> aChar; cout << "Character is " << aChar << endl; return; } Oxford University Computing Services

32 Functions Calling a function With no return type
readChar(); With return type “int” int readNumber(); int myNum = 0; myNum = readNumber(); cout << “The integer returned is “<< myNum; Func project Oxford University Computing Services

33 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)

34 Scope int myfunction () { //open ‘function’ scope if ( true ) { //open if block int mynumber=10; //declare and initialize //mynumber variable inside the ‘if’ block scope } //close if block return mynumber; //error! } //close funciton scope

35 Questions so far?

36 Functions – passing data
Pass by Value Copy of value passed to function Pass by Reference Address of value passed to function FuncRef project Oxford University Computing Services

37 Functions – pass by Value
Function arguments have been passed as value (copy) Value outside function not changed int squareByValue (int num) { return num*num; } “num” only exists inside function scope

38 Functions – pass 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; } numberRef is passed as a reference to some integer in the calling scope

39 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.

40 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 Oxford University Computing Services

41 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 student Peter; student Sarah; Oxford University Computing Services

42 So, what is OOP? Natural thinking – making our C++ code do what we expect something to do in real life. Class Member functions/methods represent real object - behaviour Member variables/data members represent real object - state Oxford University Computing Services

43 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; Oxford University Computing Services

44 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 To make a computer do anything, you have to write a computer program. When you write this program you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal When you are telling the computer what to do, you also get to choose HOW it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. You get off a plane and want to get home, how do you do it? The taxi algorithm: Go to the taxi stand. Get in a taxi. Give the driver my address. The rent-a-car algorithm: Take the shuttle to the rental car place. Rent a car. Follow the directions to get to my house. The bus algorithm: Outside baggage claim, catch bus number 70. Transfer to bus 14 on Main Street. Get off on Elm street. Walk two blocks north to house. Oxford University Computing Services

45 Operator precedence Note: Abridged version :- Full table in workbook

46 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 Oxford University Computing Services

47 C++ for Physics - Day Two

48 Today’s Topics Creating classes Member functions and Data members
Access specifiers Function Templates Pointers Interfaces Dynamic memory (a bit) Oxford University Computing Services

49 Reminder, What is OOP? Object Oriented Programming
A way of modelling individual objects in the real world Students Vehicles Buildings ATM’s etc, etc My personal opinion is that despite its slightly slower execution speed, OOP, or Object Oriented Programming, is one the best programming concept invented -- just as good as the multitasking OS and compiled libraries. OOP is really just trying to model individual objects in the world. This allows for natural-thinking -- what you would expect something to do in real life also does the same thing in code. If programmed correctly you could basically end up "speaking English" to the objects in your program or game. Users of Visual BASIC or Visual C++ will pick up this since it is an object-oriented language -- each control in the GUI is a type of object. Moving into OOP is what changes programming from decipherable code into real, understandable thought that is easy to understand. You have to keep in mind that the computer thinks in specifics. In fact so specific that the only thing the computer truly understands (if understanding is proper terminology) is "electrical signal on." Perhaps not even "off" as that is simply the absence of an "on," but that's a matter of philosophy. Another method of looking at OOP, which is just as valid, is inheritance. And instead of looking from the big to the small, you look from the generic to the specific. Try to start as generic as common sense dictates. Let's use "vehicle" as an example. What do all vehicles have in common? They all have tires and engines right? Wrong. Helicopters are vehicles and don't have tires and glider planes don't have engines. The computer takes everything 100% literally, so you have to be as specific as possible when planning your programming project. All vehicles can move -- that's what makes them vehicles. Now in our "real world," this matters worth squat since all matter can move but for a computer an object that can move can do something, and anything that happens needs to be coded. To continue, think up more specific groups, like cars, which share tires, engines, and more, and even farther to say four- door and two-door, then to specific models like a Nissan Micra, which has all of the previous features in common but has unique characteristics such as X horsepower and X size fuel tank. The point of doing this is for breaking down many complex objects and tasks into simpler subgroups which can be programmed by themselves and then used in all objects following that one. For example you could program an engine then anything that has an engine in it will use that code when they run their engine. Oxford University Computing Services

50 Reminder, what is OOP? Natural thinking – making our C++ code do what we expect something to do in real life. Class Member functions/methods represent real object - behaviour Member variables/data members represent real object - state Oxford University Computing Services

51 Classes and Objects Or your own class ‘student’ i.e. student peter;
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 string myname; string myaddress; Or your own class ‘student’ i.e. student peter; Oxford University Computing Services

52 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

53 Inheritance

54 Inheritance Staff MD Accounts Manager Sales Manager Sales Staff
Accounts Staff

55 The nitty-gritty Review of functions Classes and objects Pointers
Inheritance Dynamic memory (a bit) Interfaces (a bit)

56 Functions (review) 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 Oxford University Computing Services

57 Functions (review) Need a prototype (typically in header (.h) file)
Tells the compiler what is coming Return type Function name (Parameter list) double numDoubled(int); Defining a function (in source (cpp) file) int numDoubled(int num) { return num*num; } Pass by reference int numDoubled(int& num) { return num*=num; } Oxford University Computing Services

58 Classes and Objects (review)
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 student Peter; student Sarah; Oxford University Computing Services

59 Classes and Objects (review)
Member functions Called by objectInstanceName.functionName() Peter.displayName(); Peter.setCourseName(); Peter.setYears(); Data Members (variables of object) Member functions used to access the data members Each instance of the class has its own copy of the data members, e.g. Peter.courseName; Oxford University Computing Services

60 Classes and Objects Data Members Access specifiers
private: only accessible via member functions of the class protected: only accessed via member functions of the class and member functions of a derived class public: can be accessed from any (non-member) function, anywhere the object is visible Oxford University Computing Services

61 Classes and Objects class StudentCourse { private: string courseName;
public: void setCourseName(string name) courseName = name; } }; OxStudents Oxford University Computing Services

62 Classes and Objects Constructors StudentCourse (string cName)
Default constructors, provided by compiler takes no parameters and initializes nothing Create your own & initialise data members StudentCourse (string cName) { CourseName = cName; } Destructors Class name preceded by tilde ~ ~ StudentCourse (); Oxford University Computing Services

63 Preprocessor wrapper #indef
If class is not defined ‘ifndef’, define it If already defined, leave from compilation process Initialiser List & ifndef - define

64 Interfaces The details of HOW the class works is separate from how to interact with the objects. Interfaces define the services a class object can use (it’s member functions) Interfaces should contain no detail of how the class works Interfaces should separate the class definition from its implementation Oxford University Computing Services

65 Interfaces - How An interface defines class member functions as function prototypes but should give no detail of how the member functions are implemented. This is held in the header (.h) file. The member function implementation is held in a source code file with the same base name as the header file with .cpp extension Oxford University Computing Services

66 Interfaces Implementation file Class definition/Interface
Client Source Code Student.h Student.cpp main function .cpp Compiler Compiler Student class Object code main function Object code Student executable application Interface Project Linker Oxford University Computing Services

67

68 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 36.23 32.78 Oxford University Computing Services

69 Arrays Declaration: int inNumbers[20]; char inName[5];
an array of 20 integers char inName[5]; an array of 5 characters Declaration and initialization: double examMarks[] = {1.2, 3.9, 9.5} initialise and set size to 3 elements of type double Oxford University Computing Services

70 Arrays : Adding data double examMarks[5]; //declaration, [] is part of type //Subscript operator [] provides access to elements of array [i]. “[]” is an operator for(int i = 0; i <5; i++) { cout<<"Enter Exam Mark "<<i + 1<<" "; cin >> examMarks[i]; } [], as many things in C++, is context sensitive – behaves differently at initialization to access [] is the subscript operator Oxford University Computing Services

71 Arrays Outputting data from an array for(int i = 0; i <5; i++) { }
cout<<"Exam Mark "<<i + 1<<"is "<< examMarks[i] <<endl; } Array project Oxford University Computing Services

72 Multidimensional Arrays
67 71 61 58 Column 0 Column 1 Row 0 a[0] [0] a[0] [1] Row 1 a[1] [0] a[1] [1] Exam mark 1 Exam mark 2 Stud 1 67 71 Stud 2 61 58 Oxford University Computing Services

73 Multidimensional Arrays
Two dimensional array Two subscripts First identifies row Second identifies column double examMarks[2][2] = {0}; for(int row = 0; row < 2; row++) { for(int col = 0; col <2; col++) cout<<"Enter Exam Mark No "<<col + 1<<" for student No "<<row +1 <<" "; cin >> ExamMarks[row][col]; } cout<<endl; MultiDimArray project Oxford University Computing Services

74 Multidimensional Arrays
Two dimensional array Output array element values for(int row = 0; row < 2; row++) { for(int col = 0; col <2; col++) cout<<"Student No "<<row + 1<<" Exam Mark No "<<col <<" is "<<ExamMarks[row][col]; } cout<<endl; MultiDimArray project Oxford University Computing Services

75 Pointers A pointer types has a memory address as its value
A pointer can be used to point to the location in memory where a variable is stored Variable of type int: int a = 5; Variable of type int-pointer: int* ap; a is value pointed to by ap: int a = *ap; (note value of LHS and RHS are integers) NOTE: *used in declarations section indicates variable is a pointer. *used before a pointer elsewhere in program, references the value at the address in memory - the dereference operator Oxford University Computing Services

76 Pointers? Don’t have to be initialised when declared Can be reassigned
int* wPtr;  not initialised int* wPtr = &w;  initialised wPtr = &w;  initialised assigned wPtr = &x;  can reassign

77 Pointers, references, addresses, defreference???
int b = 5; //integer variable b; int& a = b; //a is an integer type reference to b (see slide 45) int* bp = &b; //integer pointer bp = address of b (see previous slide) a = * bp; //Set the value of the integer a to the value contained in the memory address “pointed to” by bp; The dereference operator. Example Declaration Example Initializer / RHS value 50 int b = int& a = 5; *bp; Memory (address of) 0xabc1234 int* ap = &a; &b;

78 Pointers int b = 5; //integer variable b;
int& a = b; //a is an integer type reference to b (see slide 45) int* bp = &b; //integer pointer bp = address of b (see previous slide) a = * bp; //Set the value of the integer a to the value contained in the memory address “pointed to” by bp; cout << b << endl; // returns 5 cout << a << endl; // returns 5 cout << bp << endl; // returns e.g 0x45f (memory address) cout << *bp << endl; // returns 5 (* is dereference) cout << &a <<endl; //returns e.g 0x45f (memory address) (& isaddress of)

79 Dynamic Memory allocation - no exercises on this today
int* oneCat = new Cat ..work with your cat… delete oneCat double* someCats = new Cat[5] ..iterate over all my cats delete [] someCats; Very important to delete dynamic pointer when finished and use with correct syntax Before: Everything was on the “stack” Now use heap. Ask operating system for more memory to use. Way to have Objects that live outside of any scope

80

81 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 ) Oxford University Computing Services

82 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; } Reads like replace “T” with “int”: int a=1; int b=2; int c=3; int x= maximum(a,b,c) But applies equally if a,b,c and x were floats, doubles or cabbages FunctionTemplate ArraySortVectorTEMPLATEClass Oxford University Computing Services

83 Exercises Core Language
Please either complete or understand the exercises from day 1 if you have not already Ex18*, 19, Ex24 T1*, Ex 25 T1, Ex26 T1 & T2 27, 28*, 29* T1&2, 30* The solutions are at: pnp.physics.ox.ac.uk/~brisbane/cplusplus_late st/EclipseStudentFiles_part1_answers.tgz

84 C++ for Physics – Day 3 Oxford University Computing Services 84

85 Today’s topics Inheritance again Member initialiser list
Overriding base class methods Composition Operator overloading STL (vectors and Lists)

86 Inheritance (again) Staff MD Accounts Manager Sales Manager
Sales Staff Accounts Staff

87 Inheritance Base and Derived Classes
class Manager : public Staff { Data members; Member functions; }; Base class is Staff Derived class is Manager Manager class will inherit (have access to) data members & member functions of Staff class StaffNIL

88 Inheritance access modifiers again
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 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

89 MemberInitialiser List
Manager::Manager(string name, string DOB, string DOJ, string po, string ns) without initializer {position = po; numStaff=ns; Staff = ? cant do it (or just trust default constructor) using initializer :position(po), numStaff(ns), Staff(name, DOB, DOJ) {}

90 Overriding Base Class Methods
Derived class method must match base class Same signature (i.e. name, return type and number of arguments) Beware: overriding base class methods hides ALL functions in base class with the same name Inheritance

91 Composition or Aggregation
Including objects of other classes as data members of the class Aggregation (Inheritance): Inheriting base class functionality directly Design tip: Composition - to inherit public functionality Inheritance - to inherit interface Inheritance - Iff you absolutely must, inherit private or protected functionality Composition

92 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

93 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 or removed from the end Algorithms to manipulate data Iterators (like pointers) to cycle through all elements in vector Oxford University Computing Services

94 Vectors vector<int> vec(20,0);
for(int i = 0; i<vec.size(); i++) vec[i] = (i); { cout<< vec[i]<<" "; } Oxford University Computing Services

95 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]<<" "; } Oxford University Computing Services

96 Vector member Function
Vectors Vector member Function Effect at(element number) Gets the value contained in the specified element back() Gets the value in the final element begin() Points to the first element in vector clear() Erases the vector empty() Returns true (1) if the vector is empty, or false (0) otherwise end() Points to the last element in vector front() Gets the value in the first element pop_back() Removes the final element push_back(value) Adds an element to the end of the vector, containing the specified value size() Gets the number of elements reverse(); reverse(v.begin() v.end()) An algorithm (global function) that reverses the values in a vector (v) v.begin() and v.end() are iterators sort(); sort(v.begin(), v.end()) An algorithm (global function) that sorts the vector (v) VectorPushBack.dev Oxford University Computing Services

97 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. Oxford University Computing Services

98 Lists list<double> mylist(2); mylist.push_back(7.8);
mylist.push_front(67.62); mylist.push_front(2.73); mylist.pop_back() mylist.pop_front() Oxford University Computing Services

99 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 Oxford University Computing Services

100 Exercises Ex 20, 21, 30* Note, the following are in workspace 2
31*, 32* , 33, 34, 35*, 36, 37, 38, 39, 40, 41*, 42, 43, 44*, 45 Please complete or understand the starred exercises from last time *Try to do these at a minimum

101 Other concepts (out of scope)

102 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

103 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

104 C++ for Physics – Day 4 Oxford University Computing Services 104

105 Afternoon’s Topics Polymorphism STL Abstract classes Containers
Static binding Dynamic binding Pure virtual functions Dynamic Memory STL Containers Algorithms Iterators

106 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

107 Polymorphism virtual function Functionality
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

108 Polymorphism Rectangle myRectangle; Shape* Ptr = & myRectangle;
Shape pointer points to a Rectangle object Pointer PtrP can be used to access base and derived class functions, providing the base class function is a VIRTUAL function Declaring a function as virtual in the base class virtual double area(); Ptr->area() Virtual functions

109 Polymorphism Dynamic types : Can create iterrable collections of different types of object and access the function names common to the base class Like MyObject->Draw() Can choose which class type to instantiate based on program flow or information that evolves as program executes. Can create ‘plug-ins’

110 Binding Static binding: Late (dynamic) binding: At compile time:
Rectangle myRectangle; Late (dynamic) binding: At run time: int thing; int* ptr; if (statement is true) ptr=&thing; And, using virtual functions and polymorphic base pointers *sometimes people use the phrase “dynamic binding “ to mean “determine whether the class or function even exist at runtime”

111 Abstract Classes Classes that we never instantiate
Derived classes contain detail implementation Base class data members and member functions might be difficult to define So create an abstract class and then add the specifics in the concrete class Make one of the virtual functions a pure virtual function virtual void area() = 0;

112 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

113 Standard Template Library
Containers vectors lists deques multiset multimap sequence containers associative containers Collectively known as first-class containers

114 Standard Template Library
algorithms find() sort() copy() max_element() mismatch() many many more……

115 Writing to File Open a file for writing:
Use ofstream class defined in <fstream> ofstream outFile; outFile.open(“Numbers.txt”, ofstream::out); outFile << intStore.at(count)<<endl; outFile.close();

116 Reading from File Open a file for reading:
Use ifstream class defined in <fstream> ifstream inFile; ifstream inFile( "Numbers.txt", ios::in ); int r; inFile >> r; storeSort.push_back(r); File IO

117 Standard Template Library
Iterators different types supported by each container…… random access vector, deque bidirectional list, multiset, multimap

118 Suggested exercises Complete or understand any starred exercises from previous days 46*,47*, 48* 49* 50, 51, 52 If time 53 Finally, for those of you using root in real life, run : eclipse_launch_workspace root_demo To develop ROOT applications in eclipse on pplxint8 or 9

119 Exercises Complete what you can.
Completing the suggested exercises will allow you to read most C++ programs and have enough C++ knowledge to get the job done. Completing all other exercises will further your knowledge of STL, benefit your coding style and programming efficiency and also potentially write faster programs

120 More STL (out of scope)

121 deque container Pronounced “deck”:
Double ended queue, add and remove elements at both end efficiently Elements not necessarily in contiguous memory Can still use subscript operator [] for each element Does not need complete reallocation of memory when new elements added Memory managed by class deque

122 multiset container Elements are the key values
Always ordered automatically by key multiset

123 multimap container Elements have a key and mapped value
Always ordered automatically by key multimap

124 Backups

125 Comparison of declaration and definition
You can declare something only once per compilation. Use of headers with #ifndef preprocessor wrapper You can include a definition in as many object files as you like Result of including the same headers in multiple cpp files These should be compiled separately, so it is OK They are compiled separately in eclipse. You can define it only once per program definition in cpp file cpp file is only compiled once and linked once cpp file is not #include-ed

126 C++ for Physics Oxford University Computing Services 126


Download ppt "C++ For Physics S. Brisbane Based on original slides I. Miller"

Similar presentations


Ads by Google