PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t contain every piece of information you might ever need. 2-3 Variables. Types and Names 4 Simple Maths 5 Maths functions 6 Pointers, references and Arrays 7 The stack and the heap (free store) 8-9 Functions 10 Simple I/O 11 Formatted Output 12-15 Classes 16 Strings 17 Random Numbers, Vectors 18 Iterators and Sorting 1
Variables, Types and Names Variables store information Variables have a type and a name float x = 10.0; Built-in simple types: int float double bool char Can be simple types: int x = 10; You can prevent variables being modified by declaring them const const int x = 10; Can be class types: std::string message = Hello, World ; Curly brackets denote a scope: { float x; } Variables declared inside a scope are created on the stack and deleted at the end of the scope. Variables declared outside a scope are global visible everywhere in the code and should be avoided 2
Types can be converted: implicitly: int x = 10; float y = x; explicitly: int x = 10; float y = float(10); Useful for forcing or preventing integer division: int i = 1; int j = 2; float k = i/j; // integer division k=0 k = float(i)/j; // floating division k = 0.5 Namespaces can be used to avoid naming conflicts: namespace MyNameSpace { float x; } Fully qualified name is then: MyNameSpace::x Bring names into global namespace (so you don t need fully qualified name: using namespace MyNameSpace; Or using MyNameSpace::x; 3
Simple Maths Basic operator summary pre increment / decrement post increment / decrement Multiply Divide Modulo (remainder) add subtract Less than Less than or equal Greater than Greater than or equal Equal to Not equal to Assignment = and += etc ++ a and -- a a++ and a-- a * b a / b a % b a + b a - b a < b a <= b a > b a >= b a == b a!= b a = b; a+=b; etc. Highest precedence at the top. Equal precedence in each box If in doubt use brackets! 4
Maths Functions Standard library contains a wide range of maths functions These are in the std namespace though for historical reasons many also appear in the global namespace Maths functions declared in the cmath header file 5
Pointers and References Pointers store memory addresses, they are used to point to other variables float x = 15; float * p = &x; float * = pointer to a float & = address-of 4 3 Access the thing pointed to using the dereference operator * float z = * p; r 2 1 x Arrays act like pointers: float f[3]= {1.,2.,3.}; float * p = f; p points to the first element of f 0 p References make new labels for existing variables float & r = x; They must be initialised to something when declared Most commonly used in function arguments and return values 6
Free store and the stack A stack is a type of data structure implementing a last-in first-out policy Fast efficient way to handle variables inside a scope and in function calls But limited in size Last-in first-out To access all memory and allocate large objects use the free store: Big arrays: float * array = new float[10000]; Large objects: 4 3 2 1 0 d c b a PhoneBook * obj = new PhoneBook(); If you allocate with new you must deallocate with delete delete[] array; delete obj; 7
Functions Functions package up a collection of instructions They must be declared: int myfunction(int arg1, int arg2); And defined: int myfunction(int arg1, int arg2) { return arg1+arg2; } And called using () : myfunction(5,10); You cannot define functions inside of other functions! You can use default values for arguments in the declaration: int myfunction(int arg1, int arg2=1); But the order matters: int myfunction(int arg1=0, int arg2); int myfunction(int arg1, int arg2=1, int arg3); Overloading functions: same name different arguments int add(int a, int b); float add(float a, float b); 8
Arguments passed-by-value a local copy is made that exists only within the scope of the function To modify arguments use a reference: int myfunction(int & arg1, int & arg2); To avoid copying large objects use a const reference int myfunction( const LargeObject & obj); inline functions use inline keyword to give the compiler a hint Non inline version: Functions.hpp double myfunc(double x, double y); Functions.cpp double myfunc(double x, double y) { return x+y; } Inline version: Functions.hpp inline double myfunc(double x, double y) { return x+y;} No need for functions.cpp Functions inside a class declaration automatically inline 9
Simple I/O Much input and output in C++ handled via streams Reading and writing from/to the console via two objects: std::cin std::cout Similar objects for files: std::ifstream fin( filename ); std::ofstream fout( filename ); Read and write from a stream using >> and << std::cout << Hello ; int i; std::cin >> i; Stream state: good() : previous operation succeeded, next one might work fail(): previous operation failed, next one will fail bad(): stream corrupted eof() : end of file/stream observed std::ifstream fin( file.txt ); bool isgood = fin.good(); iostream header for basic i/o std::cout, std::cin, std::endl etc fstream header for basic file i/o 10
Formatted Output Floating point numbers 3 formats: general : precision defined number of digits scientific : exponent notation, precision = digits after point fixed : integer part + precision = decimal places If the number doesn t fit it is rounded Use function calls on the stream object or manipulators: Scientific: std::cout.setf(std::ios::scientific, std::ios::floatfield); std::cout.precision(2); Fixed: std::cout.setf(std::ios::fixed, std::ios::floatfield); Reset to default: std::cout.unsetf(std::ios::floatfield); Manipulators: std::cout << std::scientific << std::setprecision(2); Set the field width with: std::cout << std::setw(4); or std::cout.width(4); Only applied to next field that gets printed Header: iomanip 11
Classes Classes add new types to the C++ language They are a collection of variables and functions A class is the description of the new type An object is variable of that type Like functions classes need a declaration: class MyClass { public: MyClass() {;} // constructor ~MyClass() {;} // destructor int publicdata; int function() const ; protected: int privatedata; private: }; And a definition: int MyClass::function() const { return privatedata; } Access controlled encapsulation: public: visible to all protected: visible only to this class and inherited classes private: visible only to this class 12
Constructors can have initialisers to setup the data members: MyClass(int d) : privatedata(d) {;} Destructor needed when there is something to clean up such as memory allocated on the free store: ~MyClass() { delete somememoryallocation; } Member functions that do not modify the object should always be declared const int function() const {return privatedata;} Access class members using dot notation: MyClass obj; int v = obj.function(); Or using pointer notation: MyClass * p = new MyClass(); int v = p->function(); When executing a member function the special variable this points to the object on which the function was called int MyClass::function() const { return this->privatedata; } 13
More on classes C++ allows the redefinition of the standard operators for new class types Two forms can be used, member or non-member: Example for a binary operator Use this for your own classes MyClass MyClass::operator+( const MyClass & obj) const; Use this to extend existing classes MyClass operator+(const MyClass & obj1, const MyClass & obj2); Members can be shared across instances of a class by labelling them with the static keyword Call static functions with: MyClass::DoSomething(); class MyClass { //.. Some code // static float staticdatamember; static void DoSomething() {} // static function }; Also need to define the storage for static data members somewhere (typically in the class cpp file) outside any scope float MyClass::staticDataMember; 14
Inheritance and Polymorphism Define inheritance relationship between two classes: class Child : public Parent { // some class declaration }; Child inherits everything from the Parent. But only protected and public members are visible Initialise the base class by calling the constructor: Child() : Parent() {;} Polymorphism enabled through pointers and virtual functions class Parent { // some code virtual void DoSomething() { // //} }; Virtual means that you can use pointers to the parent class but when you call the virtual function it will call the appropriate method in the derived class rather than in the parent 15
Strings C-style strings are just arrays of char terminated with a 0 char c[20] = Hello World ; Many standard library functions and classes make use of them C++ style strings are a new type or class : std::string std::string str( Hello World ); std::strings have lots of useful properties: length: Header str.size(); // = 11 string character access: str[3]; // = l can be appended-to str.append(! ); // = Hello World! str+=(! ); // = Hello World!! Substrings: std::string sub = str.substr(6,5); // = World Get a c-style string: str.c_str(); 16
Random Numbers Generate pseudo-random integers with std::rand() Seed the random number generator with std::srand( an integer ); Get a random number between 0 and RAND_MAX int r = std::rand(); Header cstdlib Vectors Smart replacement for arrays Header vector std::vector< type > myvector; Add myvector.push_back(value); Remove myvector.pop_back(); Size myvector.size(); Access myvector[i]; // no range checking myvector.at(i); // with range checking Clear myvector.clear(); // empty the vector 17
Iterators Used for looping over collections such as vector Header Get an iterator to the start of the collection with: vector vec.begin(); An iterator pointing one spot beyond the last element with: vec.end(); Go to the next element with: ++iter; Get the value of the element with: *iter; std::vector<int> myvec; for( std::vector<int>::iterator iter = myvec.begin(); iter!=myvec.end(); ++iter) { int x = *iter; } Very useful with standard algorithms such as sort std::sort( begin, end); Header algorithm Will sort a collection where begin is an iterator pointing to the beginning and end is an iterator pointing to one element beyond the end 18